Arrays in Java



Variables are used to store values. So far we have learnt about storing a single value inside a variable.

Now suppose you have a condition where you need to store multiple values of similar type and category, in this case are you going to create multiple variables to store all these values?

Let’s give you an example. Suppose you run a shop where you maintain a database containing product names.

Now, to store multiple product names, you just can create an array where you can store all the product names at a single location.

Array can contain different types of variables. But remember one array cannot contain two different types of variable. If you want to store two types of variables, you need to create two different arrays of required types.

In order to use an array, first we have to declare the array and then we can assign the values inside the array.

We are going to be learning non primitive data types while we learn array. Students who have already learnt C++ must have learnt about array because array is a common chapter in both Java and C++. In both the programming languages you will get to learn array.

Let’s understand the concept of array with an example. Let’s assume there is a student and we want to store the marks obtained by students in an array. There will be many subjects and in future the subjects may add also.

Now what will you do? Will you create every time a new variable for storing student’s mark. No, there is a better solution in java. Rather than making multiple variables and creating a complicated program, we can just create a list of items consisting of same data types.

We will create a list of marks of same type (integer) to store the values. The data here are getting stored in the form of a list. These data will be used later in the programming.

We hope that you have get some basic idea about array in Java. Array is very important concept in Java as well as in any programming language.

 

Syntax of an Array:

Type[] arrayName = new Type[size];

 

The above piece of code is written while declaring an array. First we have to declare which type of array we are going to create. Then we have to use square brackets, in Java wherever we see a pair of square brackets we should understand we are dealing with an array.

After using the square brackets we put a name to our array and then we write equal to symbol followed by the word “new”. Like “break” or “return” in java “new ” is also a keyword. In order to occupy new spaces in the memory by creating a variable of non primitive type we use the keyword “new” in Java.

After “new” keyword we have to write again the type of the array, the same which we had written at the beginning of the syntax. Then we write size of our array inside a square bracket. The syntax ends with a semicolon.

Since array in Java is nothing but a variable consisting of list, hence we have to declare the size of our list in the syntax itself.

For example, if we have to store the marks of student in an array, we have to write the java as follows.

 

         int[] marks = new int[8];

In above example we are storing marks of 8 subjects. If we have to store marks of more subjects we just have to change the size of the array.

Let us now visualize what is happening inside the memory after declaring an array. There will be 8 numbers of storage assigned for each subjects as shown below. Marks of different subjects will be stored in those storages.

 

Bengali

English

History

Geography

Science

Math

Computer

Music

0

1

2

3

4

5

6

7

 

There are fixed number of these memory boxes and those numbers will help you access specific data of an array. For example the first places of an array is numbered by 0, the second space is numbered by 1 and so on.

If we have to access the marks of Math subject, we can simply access the same by marks[5] as the math subjects’ mark is stored in the 5 numbered box of the array.

If we have to store computer’s marks as 75 we just have to assign the same as below.

marks[6] = 75;

Similarly, we can store the marks of other subjects as well. You have to keep in mind that the numbering of an array’s memory starts from only ‘0’. Since the indexing of Java array starts from ‘0’, hence it is called zero-indexed array.In some programming languages indexing starts from 1 as well.

 

In order to access the values stored in any array we just have to write the name of the array and inside a pair of square bracket we have to mention the index position.

          System.out.println(marks[0]);

 

The above print statement will print the value stored in the 0th position of array “marks”. Similarly we can print the values stored in other index position as well. That’s how the marks of a student in different subjects is stored in an array and can easily be accessed as well.

Now let’s see a complete coding example of an array including declaration of an array, value assigning and accessing those values.

package FirstJava;

 

public class JavaArray {

 

     public static void main(String[] args) {

 

          int marks[] = new int[3];

         

          marks[0]=97;

          marks[1]=95;

          marks[2]=99;

         

          System.out.println(marks[0]);

          System.out.println(marks[1]);

          System.out.println(marks[2]);

     }

 

}

 

 

Output in the Console:

97

95

99

Remember that when we will be printing the values stored in an array we have to specify the index position of the array which we want to print, otherwise the program will not print the values stored in the array and it will print some jargon values.

We can also print of the values stored in the array with the help a loop.

 

How an Array Values stored in Computer Memory:

As soon we create any array in Java programming, immediately the computer reserves spaces in the memory. Suppose there are 3 numbers stored in the array, then memory will also be reserved accordingly.

Each memory location will have a unique memory address in hexadecimal form. Since an integer variable’s size is 4 bytes, there will be 12 bytes occupied in the memory for storing 3 integer values.

In the below table, we have memory address written in numbers, however actual memory address will be written in hexadecimal form. Each memory address size is 1 byte.

The first four memory location reserves the value of first subject and so on. The memory is allocated in linier fashion. Which means each memory location’s address will be greater than the previous memory location’s address.

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

Total 04 bytes

Total 04 bytes

Total 04 bytes

 

 

Alternate way of Array declaration:

The array can be declared in other ways as well. Check the below syntax.

 

Type [] arrayName = {10,20,30,40,50};

 

 

In this type of declaration we already know from the beginning the actual size of the array. We declare as well as assign values to array at the same time.

 

As there are 5 values in the array, the memory will automatically get allocated for 5 integer values. If we know the elements of an array  from the beginning, we can create an array like this.

 

 

User Input in Java Array:

 

User input is very important in Java. The size of an array can be specified by a user and memory will be allocated according to the size given by the user.

 

package FirstJava;

 

import java.util.Scanner;

 

public class JavaArray {

 

     public static void main(String[] args) {

 

         

          Scanner sc = new Scanner(System.in);

 

          System.out.println("Enter Array Size");

         

          int size = sc.nextInt();

         

          int marks[] = new int[size];

         

          for (int i=0;i<size;i++) {

              System.out.println(marks[i]);

          }

         

         

     }

 

}

 

In the above program we have taken the size of the array as user input. We created an object of Scanner class.

 

A “size” variable has been created which is of integer type and the value of size is being is being taken by user input.

 

As we run the program, it automatically asks for an user input of integer value. Whatever value is input by the user will be stored in “size” variable and an array of same size will be created.

 

Now, with the help of for loop we can print the elements of the array.

 

Although the array values were not provided, when we run the program, we see that whatever size had been given by the user as input, same number of “zero” is printed. Then where did those zeroes come from?

 

The answer is unassigned array gets automatic a value of zero or null value if not initialized. Similarly other data types in array gets auto initialized with respective values such as float array is auto initialized by 0.0, string array gets auto initialized by an empty string and so on.

 

If the array is initialized with a proper value at the time of its declaration, then the given value is stored inside the array instead of null value.

 

Unlike Java, in C++ programming language, any uninitialized array is auto initialized by some garbage values. This is a benefit in Java programming language because if you have created an array and you do not know which data will be stored in the array in future, the array will be automatically initialized.

 

Lets us see now how to write a program which will take input from the users marks obtained in different subjects and later print those values.

package FirstJava;

 

import java.util.Scanner;

 

public class JavaArray {

 

     public static void main(String[] args) {

 

         

          Scanner sc = new Scanner(System.in);

         

          int marks[] = new int[4];

          String[] subs = {"Bengali", "English", "Math", "Science"};

         

          for (int i=0;i<4;i++) {

              System.out.println("Enter the marks of "+ subs[i]);

              marks[i]=sc.nextInt();

          }

         

         

          for (int i=0;i<4;i++) {

              System.out.println("Marks obtained in "+ subs[i]);

              System.out.println(marks[i]);

          }

         

         

     }

 

}

 

 

How to ascertain the length of an array:

There is a length attribute associated with each array. This variable helps us get the size of an array.

For example we declare an array which will store the ages of students. By default we assign some values as well inside the array.

Now in order to get the size of the array we just simply run the below code.

 

int [] ages = {"24", "22", "21", "23"};

 

            int size = ages.length;

 

 

This code will store the size of the array inside the “size” variable, which can later be used in different purposes in programming.

 

Java Exercise (Array):

Question:

Create a string array to take input of few names from the user and later print those names on the screen.

Solution:

package FirstJava;

 

import java.util.Scanner;

 

public class JavaArray {

 

     public static void main(String[] args) {

 

          Scanner sc = new Scanner(System.in);

          System.out.println("How many names do you want to enter?");

          int size = sc.nextInt();

         

          String names[] = new String[size];        

         

         

          for (int i=0; i<size; i++) {

              System.out.println("Enter Name "+(i+1));

              names[i] = sc.next();

          }

         

          System.out.println("Names you have entered are:");

          System.out.println("**************************");

         

          for (int i=0; i<size; i++) {

              System.out.println((i+1)+"."+names[i]);

          }

 

         

         

     }

 

}

 

Conclusion:

Hope you have understood the concept of array in Java. We will learn more about Java programming in our next lesson.

Arrays in Java Arrays in Java Reviewed by Technobits on November 03, 2022 Rating: 5

No comments:

Powered by Blogger.