Java Arrays: //it Creates An Array Reference On The Stack
Java Arrays: //it Creates An Array Reference On The Stack
Java Arrays
Arrays are objects or fundamental constructs which store multiple variables of the same type.
It can hold primitive types as well as object references. In fact most of the collection types
in Java which are the part of java.util package use arrays internally in their functioning.
Since Arrays are objects, they are created during runtime.
Or Arrays are variables used to store multiple values in a single variable, instead of declaring
separate variables for each value.
2. Features of Array
Arrays are objects
They can even hold the reference variables of other objects
They are created during runtime
They are dynamic, created on the heap
The Array length is fixed
3. Array Declaration
The declaration of array states the type of the element that the array holds followed by the
identifier and square braces which indicates the identifier is array type.
Syntax:
int values[]; //it creates an array reference on the stack.
or
int []values;
To declare an array, define the variable type with square brackets: similarly
String[] cars; // a variable cars that holds an array of strings.
- The array elements are accessed through the index that is, they start from 0
to (array_name)values.length-1.
Example1
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
double[] myList = new double[10];
Following picture represents array myList where it holds ten double values and the indices
are from 0 to 9.
-if we did not store any value to an array, the array will store some default value such as 0
for int, false, etc.
-The array elements can be accessed with the help of the index. myList[0] refers to 1 , myList
[1] refers to 2 etc. we can access up to myList[n-1] where n is the size of the array. Accessing
the array with an index greater than or equal to the size of the array leads to Array
Indexoutofbounds exception
Example2: array with default value
class array
{
public static void main(String[] a)
{
int age[]=new int[5];
System.out.println(0);
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
}
Here all the elements of the array will be initialized to 0 as it’s created on the heap.
Example3:
Accessing array elements using for loop
class array
{
public static void main(String[] a)
{
int age[]=new int[5];
for(int i=0;i<5;i++) // or i<age.length
System.out.println(age[i]);
}
}
for loop and the length property are used to specify how many times the loop should run.
The following example outputs all elements in the cars array:
Example5
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++)
{
System.out.println(cars[i]);
}
Example5:
The below example initializes the array elements to 1,2,3,4,5,6 and prints them.
class array1
{
public static void main(String args[])
{
int FirstArray[] = new int[6];
for(int i=0;i<FirstArray.length;i++)
{
FirstArray[i]=i+1;
}
for(int i=0;i<FirstArray.length;i++)
{
System.out.println(FirstArray[i]);
Sytem.out.println(FirstArray.length);
}
}
}
Garbage collection and Arrays
If we declare
int aiFirstArray=null; //nullify the reference variable
Test t=new Test()
t=null;
Example6
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars)
{
System.out.println(i)
}
The example above can be read like this: for each String element (called i - as in index)
in cars, print out the value of i.
If we compare the for loop and for-each loop,
for-each loop is easier to write, it does not require a counter (using the length property),
and it is more readable.
Example7
//return largest element from an array
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 125, 132, 95, 116, 110 };
int highest_marks = maximum(marks);
System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int max= numbers[0];
// for each loop
for (int num : numbers)
{
if (num > max)
{
max= num;
}
}
return max;
}
}
1) For-each loops are not appropriate when you want to modify the array:
for (int num : marks)
{
// only changes num, not the array element
num = num*2;
}
2) For-each loops do not keep track of index. So we can not obtain array index using for-
Each loop
for (int num : numbers)
{
if (num == target)
{
return ???; // do not know the index of num
}
}
3) For-each only iterates forward over the array in single steps
// cannot be converted to a for-each loop
for (int i=numbers.length-1; i>0; i--)
{
System.out.println(numbers[i]); //not possible
}
4) For-each cannot process two decision making statements at once
// cannot be easily converted to a for-each loop
for (int i=0; i<numbers.length; i++)
{
if (numbers[i] == arr[i])
{ ...
}
}
In such case, data is stored in row and column based index (also known as matrix form).
Example8
int[][] arr=new int[3][3]; //3 row and 3 column
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example9
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
To access the elements of the myNumbers array, specify two indexes: one for the array, and
one for the element inside that array. This example accesses the third element (2) in the
second array (1) of myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x); // Outputs 7
We can also use a for loop inside another for loop to get the elements of a two-dimensional
array (we still have to point to the two indexes):
Example8
public class MyClass
{
public static void main(String[] args)
{
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i)
{
for(int j = 0; j < myNumbers[i].length; ++j)
{
System.out.println(myNumbers[i][j]);
}
}
}
}
9. Multidimensional Array
//Java Program to illustrate the use of multidimensional array
class Testarray
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
class sortNumbers
{
public static void main(String[] args)
{
int[] data={40,50,10,30,20,5};
System.out.println("Unsorted List is :");
display(data);
System.out.println("\nSorted List is :");
display(data);
}
static void display(int num[])
{
for(int i=0; i<num.length;i++)
System.out.print(num[i] + " ");
}
}
}
Special Version of Multidimensional Array called Jagged Array. If we are creating odd
number of columns in a 2D array, it is known as a jagged array. In other words, it is an array
of arrays with different number of columns. This array is also known as “Ragged array” and
is basically an array of arrays.
It is an array of arrays where each element is, in turn, an array. A special feature of this type
of array is that it is a Multidimensional array that’s each element can have different sizes.
A two-dimensional array in Java is an array of single dimension array. In the case of a two-
dimensional array, each one-dimensional array will have different columns.
//Java Program to illustrate the jagged array
class TestJaggedArray
{
public static void main(String[] args)
{ //declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
//printing the data of a jagged array
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Above shown is a two-dimensional Jagged array. Each individual element of this array is a
one-dimensional array that has varied sizes as shown above.The first 1D array has 3 columns;
the second row has 2 columns while the third has 4 columns.
Once the array is declared, you can define it as a Jagged array as shown below:
myarray[1] = new int[2];
Once the array is created, we can initialize it with values. Note that if we don’t explicitly
initialize this array (as in the above case), then it will take the default values as initial values
depending on the data type of the array.
We can also omit all the new operators altogether and have a declaration and
initialization statement as shown below.
int[][] arr = {
{ 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 8, 9 } };
The program below initializes a ragged array by assigning initial values to each row.
Here each row of the array is initialized to the column values.
Example 10
class Main
{
public static void main(String[] args)
{
// Declare a 2-D array with 3 rows
int myarray[][] = new int[3][];
// define and initialize jagged array
myarray[0] = new int[]{1,2,3};
myarray[1] = new int[]{4,5};
myarray[2] = new int[]{6,7,8,9,10};
// display the jagged array
System.out.println("Two dimensional Jagged Array:");
for (int i=0; i<myarray.length; i++)
{
for (int j=0; j<myarray[i].length; j++)
System.out.print(myarray[i][j] + " ");
System.out.println();
}
}
}
As shown in the output, the first row of Jagged array has 3 columns, the second row has 2
columns and the third row has 5 columns.
Example11
Given below is an example of a Jagged array in Java. Here the array is initialized using for
loops.
class Main
{
public static void main(String[] args) {
// Declaring 2-D array with 4 rows
int intArray[][] = new int[4][];
// create a jagged array
intArray[0] = new int[3];
intArray[1] = new int[2];
intArray[2] = new int[1];
intArray[3] = new int[4];
// Initializing array with values
for (int i=0; i<intArray.length; i++)
for(int j=0; j<intArray[i].length; j++)
intArray[i][j] = (i+1) * (j+1); //initial values for each row,column
// display the contents of 2-D jagged array
System.out.println("Two-dimensional Jagged Array:");
for (int i=0; i<intArray.length; i++)
{
for (int j=0; j<intArray[i].length; j++)
System.out.print(intArray[i][j] + " ");
System.out.println();
}
}
}
The above program defines a Jagged array of 4 rows. The column numbers of each row are
then defined thereby creating an array of arrays. Then using for loops that traverse both rows
and columns, the initial values are assigned to this array. The array is then printed using for
loops.
Example12
class Main
{
public static void main(String[] args)
{
// Declare a 2-D array with 5 rows
int intArray[][] = new int[5][];
// create a jagged array that has i column(s) for ith row
for (int i=0; i<intArray.length; i++)
intArray[i] = new int[i+1];
// Initialize the jagged array
int count = 0;
for (int i=0; i<intArray.length; i++)
for(int j=0; j<intArray[i].length; j++)
intArray[i][j] = count++;
// Display the values of 2D Jagged array
System.out.println("A two-dimensional Jagged Array contents:");
for (int i=0; i<intArray.length; i++)
{
for (int j=0; j<intArray[i].length; j++)
System.out.print(intArray[i][j] + " ");
System.out.println();
}
}
}
The above program output shows that each row has the number of columns equal to the
corresponding row number. The elements are initialized to a sequence starting from 0.