Learn java array

Hey guys!! Welcome to flower brackets blog. Today you will learn java array.

So, what are arrays and how we can declare and use arrays in java.

An array is same as a variable. It can store more than one value at a time. But the condition with array is you need to store, rather only store same kind of values.

Learn Java Array

For example, say you want to store 20 integers in an array, you can do it. But if you want to store 10 integers and 5 double values you can’t do it.

public class SampleExample
{
   public static void main(String[] args)
   {
      int[] arr = {1,2,3,4,5};
   }
}

For example, to create an integer array give the data type, use square brackets and give the variable name “arr”.

Initialize “arr” in curly braces 1, 2, 3, 4, 5. These are the values or elements of the array. We have stored five integers in this array.

Also read – array java

Now there are different ways of declaring array and the most basic one is mentioned in the above example. The different ways are,

public class SampleExample
{
   public static void main(String[] args)
   {
      int[] arr = {1,2,3,4,5};
      int[] arr = new int[5];
      int[] arr = {1,2,3};
      int[] arr = new int[]{1,2,3};
   }
}

For example I want to print the value 2,

public class SampleExample
{
   public static void main(String[] args)
   {
      int[] arr = {1,2,3,4,5};
      System.out.println(arr[1]);
   }
}

Actual position of 2 is 1. In this way you can access the value of array.

In case if you want to print all the values in the array we use while loop to print all the values in the array like this,

public class SampleExample
{
   public static void main(String[] args)
   {
      int[] arr = {1,2,3,4,5};
      int a = 0;
      while(a < 5)
      {
         System.out.println(arr[a]);
         a++;
      }
   }
}

Output:

1
2
3
4
5


Multidimensional array

public class SampleExample
{
   public static void main(String[] args)
   {
      int multiArray[][] = {{1,2,3,4},{5,6,7,8}};
   }
}

Here “multiArray” is name of the array and instead of just one square bracket you actually have two. The first one is for the row and the second one is for column.

Also read – 2d array java

So when you want to access elements, say first row,

multiArray[0][1] = 1
multiArray[0][2] = 2
multiArray[0][3] = 3
multiArray[0][4] = 4

Second row,

multiArray[1][0] = 5
multiArray[1][1] = 6
multiArray[1][2] = 7
multiArray[1][3] = 8

So that’s how you call elements in a multidimensional array.

Related Posts