Java Arrays

18-Sep-2024

Learn how to declare, initialize, and use arrays in Java for storing data.



In Java, the array is index-based, the first element of the array is stored at index 0 and the second element is stored at index 1. In this way, the rest of the elements are arranged according to the index.



String[] favourite_languages = {"Java", "Kotlin", "C++", "Python", "JavaScript", "Php"};



Syntaxt:



data_type[] array_name = {value1, value2, value3};





Another approach to create the Array:


If you want to create an empty array with the size and later initialize the value you can do this.

First you need to create an emtpy array with the size.



String[] favourite_languages = new String[6];


Then Access each element using index and initialize the value.



favourite_languages[0] = "Java";
favourite_languages[1] = "Kotlin";
favourite_languages[2] = "C++";
favourite_languages[3] = "Python";
favourite_languages[4] = "JavaScript";
favourite_languages[5] = "Php";


You can create an array using any of these two approach.



Let's visualize the topic through the first example






Access The Element:


Suppose we need to access the element java then we need to use the 0 index of this array. and for python we need to use the 3 index.

Now, how to access and print the value of the element? For this, we need to take a simple step. first, write the array name, and next the square bracket. In the square bracket, we need to provide the index of which element we want to access or print



System.out.println(favourite_languages[0]); // access the element Java
System.out.println(favourite_languages[3]); // access the element Python



Output:



Java Python



Change array element:


For Changing the array element first you need to access the array element then give = value ( according to array data type) it will change the array element value.  Print the element after changed to confirm.



favourite_languages[0] = "C#"; // change the element value from Java to C#
favourite_languages[3] = "Rust"; // change the element value from Python to Rust#

System.out.println(favourite_languages[0]); // access the changed element
System.out.println(favourite_languages[3]); // access the changed element



Output:



C# Rust


The next chapter we will learn about the array length and print all the array element using loop

Comments