Java Arrays

Here is a description of Java Arrays with the hope of helping you learn about them.

Java arrays contain elements with similar data types.

Java arrays

An array’s elements are also stored in a contiguous memory location. Basically, it’s a data structure for storing similar elements.

A Java array can only hold a fixed number of elements.

Arrays In Java

The purpose of Java Arrays is to store multiple values in one variable as opposed to declaring separate variables for each value.

Arrays are declared by defining the variable type with square brackets:

String[ ] country_names;

A string array has now been declared as a variable. Using an array literal, we can insert values into it – place the values inside curly braces, comma-separated:

String [ ] country_names = {"United Kingdom", "United States of America", "Berlin", "Finland"};

Arrays of integers can be created as follows:

int [ ] even_Num = {0,2,4,6,8,10};


Array elements can be accessed

The index number of an array element is used to access an element of a Java array.

According to this statement, sports_cars have the following value as the first element:

Example: 

public class Main { public static void main(String[] args) { String[] sports_cars = {"Lamborghini", "Bugatti", "Ferrari", " Porsche"}; System.out.println(sports_cars[1]); // The Second Element of the sports_car array is "Bugatti" as it has index number = 1 } }

Reminder: An array’s index starts at zero: [0] which contains the first element. Similarly, [1] is the second element and so on.

Accordingly, in order to print the name of “Atlanta Hawks” we use the index number 3.

Example: 

public class Main { public static void main(String[] args) { String[] NBA_teams = {"Boston Celtics", "Brooklyn Nets", "Detroit Pistons", "Atlanta Hawks"}; System.out.println("My favorite team is: "+NBA_teams[3]); // We used the index number 3 to access the name of "Atlanta Hawks". } }

Array element changes

Refer to the index number to change the value of a specific element:

Example

sports_cars[2] = "Aston Martin";

Example: 

public class Main { public static void main(String[] args) { String[] sports_cars = {"Lamborghini", "Bugatti", "Ferrari", " Porsche"}; sports_cars[2] = "Aston Martin"; System.out.println(sports_cars[2]); // The value at index [2]= Ferrari, has now been updated to "Aston Martin" } }

We can also change the value of multiple elements, as shown below:

programming_Languages[0] = “Java Programming language”;
programming_Languages[1] = “Python Programming language”;
programming_Languages[2] = “C Programming language”;
programming_Languages[3] = “C sharp Programming language”;

Example: 

public class Main { public static void main(String[] args) { String[] programming_Languages = {"Java", "Python", "C", "C#"}; programming_Languages[0] = "Java Programming language"; programming_Languages[1] = "Python Programming language"; programming_Languages[2] = "C Programming language"; programming_Languages[3] = "C sharp Programming language";for(int mrx=0;mrx<=3;mrx++) { System.out.println(programming_Languages[mrx]); } } }

Array Length

As opposed to C/C++, we can get the length of an array using the length member. The sizeof operator is required in C/C++.

An array’s length property tells how many elements it has:

Example: 

public class Main { public static void main(String[] args) { String[] sports_cars = {"Lamborghini", "Bugatti", "Ferrari", " Porsche"}; System.out.println(sports_cars.length); } // Output returns 4 which is the length of the above given array. }

Example: 

public class Main { public static void main(String[] args) { String[] MLB_team_players = {"Cory Abbott", "CJ Abrams","Albert Abreu","Bryan Abreu","José Abreu","Willy Adames","Ehire Adrianza","Ryan Aguilar","Sergio Alcántara"}; System.out.println(MLB_team_players.length); } // Return : Returns 9 as there are 9 elements in this array. }

Loop Through an Array

Array elements can be looped by using the for loop, where the length property specifies how many times the loop should run.

Following is an example that outputs all elements from the sports_cars array:

Example: 

public class Main { public static void main(String[] args) { String[] sports_cars = {"Lamborghini", "Bugatti", "Ferrari", "Porsche"}; for(int mrx=0; mrx < sports_cars.length; mrx++){ System.out.println(sports_cars[mrx]); } } // Output : // Lamborghini //Bugatti //Ferrari //Porsche }

Example: 

public class Main { public static void main(String[] args) { String[] pillars_Of_OOP = {"Abstraction","Encapsulation","Inheritance","Polymorphism"}; for (int ample=0;ample <= 3;ample++){ System.out.println("Pillars Number "+ample+" : "+pillars_Of_OOP[ample]); } }// Output:// Pillars Number 0 : Abstraction // Pillars Number 1 : Encapsulation // Pillars Number 2 : Inheritance // Pillars Number 3 : Polymorphism}

For-Each loop through an array

The for-each loop is exclusively used to loop through array elements:

Syntax:

for (type variable_name : arrayname) {
...
}

Using a “for-each” loop, the following example outputs all elements in the sports_cars array:

Example: 

public class Main { public static void main(String[] args) { String[] sports_cars = {"Lamborghini", "Bugatti", "Ferrari", "Porsche"}; for(String mrx : sports_cars){ System.out.println(mrx); } } }

Java arrays example

This example can be read like this: for each String element (called mrx – as in index) in sport_cars, display the value of variable mrx.

When comparing for loops with for-each loops, you will find that the for-each method is easier to write, does not require a counter (length property), and is more readable.

Example: 

public class Main { public static void main(String[] args) { String[] NFL_players = {"Tom Brady","Aaron Rodgers","Patrick Mahomes II","T. J. Watt","Deshaun Watson"};for(String ample: NFL_players){ System.out.println(ample); } }// Output:// Tom Brady // Aaron Rodgers // Patrick Mahomes II // T. J. Watt // Deshaun Watson}

Multidimensional Arrays:

In Java Arrays, a multidimensional array is an array containing more than one array.

A two-dimensional array is created by adding each array within its own curly brace:

Example

int [ ][ ] my_Numbers = { {1, 2, 3, 4, 5}, { 6, 7,8, 9,10} };

As we discussed in Java Arrays, my_Numbers is an array that contains two arrays as its elements.

Access Elements

In order to access the elements of the my_Numbers array, you must specify two indexes: one for the array, and one for its element.

Here is an example of accessing the fourth element (7) of the second array (2) of my_Numbers:

Example: 

public class Main { public static void main(String[] args) { int[][] my_Numbers={{0,2,4,6,8,10},{1,3,5,7,9}}; System.out.println(my_Numbers[1][3]); // [1] represents the rows number2 as row number starts with 0, whereas [3] represents the index number of the element to be accessed } // Output =7 }

To print an alphabet “E” from the multidimensional array refer to the example given below:

Example: 

public class Main { public static void main(String[] args) { char[][] my_Alphabets={{'A','B','C','D','E'},{'a','b','c','d','e'}}; System.out.println(my_Alphabets[0][4]); // [0] represents the number of row, whereas [4] represents the element } // Output = E }

for loops inside for loops are also useful to get the elements of two-dimensional arrays (although the indexes are still needed):

Example: 

public class Main { public static void main(String[] args) { int[][] my_Numbers={{0,2,4,6,8},{1,3,5,7,9}}; for(int rows=0; rows < 2; rows++){ for(int columns=0; columns < 5 ; columns++){ System.out.println(my_Numbers[rows][columns]); } } // Output = 0,2,4,6,8,1,3,5,7,9 } }

Example: 

public class Main { public static void main(String[] args) { char[][] my_Alphabets={{'A','B','C','D','E'},{'a','b','c','d','e'}}; for(int mrx=0; mrx < 2; mrx++){ for(int ample=0; ample < 5 ; ample++){ System.out.println(my_Alphabets[mrx][ample]); } } // Output =// A // B // C // D // E // a // b // c // d // e} }

Change Element Values

An element’s value can also be changed:

Example: 

public class Main { public static void main(String[] args) { int[][] my_Numbers={{0,2,4,6,8,10},{1,3,5,7,9}}; my_Numbers[1][3]=14; System.out.println(my_Numbers[1][3]); // value at indexes has been modified to 14 from 7; } // Output =14 }

Example: 

public class Main { public static void main(String[] args) { int[][] mrx_Nums={{5,10,15,20,25,30},{10,20,30,40,50}}; System.out.println("Previous value of 3rd element of row 2: "+mrx_Nums[1][2]); mrx_Nums[1][2]=35; System.out.println("Modified value of 3rd element of row 2: "+mrx_Nums[1][2]); // value at indexes has been modified to 30 from 35; } // Output :// Previous value of 3rd element of row 2: 30 // Modified value of 3rd element of row 2: 35 }

Java Arrays Advantages

The optimization of code ensures that the data can be retrieved or sorted efficiently, and the code is optimized.

Data can be accessed randomly at any index position.

Java Arrays Disadvantages

Array elements can only be stored in fixed sizes. At runtime, it does not grow in size. Using Java’s collection framework, this problem can be solved automatically.

 

 

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *