Header Ads

Header ADS

Arrays in java

 Arrays in java :

Arrays in Java is similar to that of C++ or any other programming langauage. An array is a data structure which holds the sequential elements of the same type.
Let’s say you want to store 50 numbers. Instead of declaring individual variables, such as number0, number1, … and so on. You can declare one array variable – “numbers” and use number[0], number[1] to represent individual variables. This will ease your task and minimizes the redundancy.
Each array has two components: index and value. Refer to the below image for better understanding:
what-is-arrays-in-java,arrays in java
Arrays in java

Here the indexing starts from zero and goes till (n-1) where n= size of the array. Let’s say you want to store 10 numbers, then the indexing starts from zero and goes till 9.
There are two types of arrays in Java:
  • Single-dimension Array
  • Multi-dimension Array
Single-dimension Arrays in java : In a single-dimension array, a list of variables of the same type can be accessed by a common name. You can initialize the array using the following syntax:
int a[] = new int[12];
You can refer to the below image where I have stored data with respect to the given index.
Single-array-in-java,array-in-java
single array in java

Multidimension Arrays in java : In a multi-dimension array, your data is stored in a matrix form. Here, you can initialize the array using the following syntax:
int table[][]= new int[4][5];
It is quite similar to the matrix that we use in mathematics. Refer to the below image where I have stored data with respect to different dimensions.
Multi-array in java,arrays in java
Multi-array in java

Thus, arrays help you in optimizing the code where you can insert the data at any location. 
Let’s see the below code to understand the concept of array in Java.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;
public class ArrayExample {
      public static void main( String args[])
     {
     double invoice[][]= new double[10][2];  // Initializing array
          Scanner obj= new Scanner(System.in);    // creating a scanner object to take input from user
          for(i=0;i<10;i++){                       // nested for loops
              for(j=0;j<2;j++);
               {
               System.out.println("Enter the value");
               invoice[i][j]=obj.nextDouble();         // store values to array   
          for(i=0;i<10;i++){
              for(j=0;j<2;j++)
               {
                System.out.println(invoice[i][j]);
               }
         }
     }
}
In the above code, I have explained how you can take input for the array and print the same.
I hope you guys are clear with how an array looks like and how do you initialize one.
 Now, let’s summarize the above topics and see the entire structure of a Java program.

No comments

for more information plz do comment and follow my blog.

Powered by Blogger.