Simple explanation of Java Arrays

Simple explanation of Java Arrays

You must have always wondered about how a menu is created or how values or elements are added to a list or menu. The Java Arrays come in handy in these types of situations. If you are a maths student you must have studied in your junior classes about Sets (set A {1,2,3}) arrays that are similar to Sets. They contain elements under a single name or store values in them. The array works differently in Java than in C/C++.

What is a Java Arrays?

Java arrays are objects that hold a number of values of the same data types stored at contiguous memory locations. The size must be defined using int or short value but not by long. Depending on how the array is specified, it may contain both object (or non-primitive) references to members of a class and primitives (such as int, char, etc.). The actual values for primitive data types are kept in a group of related memory regions. There are various kinds of arrays that are used to store data i.e. single dimensional arrays and multidimensional arrays, we will come back to both topics first, and let us see how to initialize an array.

Also read, Simple explanation of Java Operators

How to create an Array?

We can initialize and declare an array in two ways, the first is by implementing new keywords and initializing it one by one and the second is by implementing curly braces.

Initializing with a new keyword

dataType [ ] nameOfArray;
  • dataType: the kind of data you intend to include in the array. This could be a double, integer, string, or another type.
  • [ ]: Indicates that an array of values will be present in the variable to be declared.
  • nameOfArray: array identifier.
dataType [ ] nameOfArray = new dataType [size]

Typically, the size is stated as a numerical value. It designates how many values you want the array to store. Since you cannot add more than the amount provided as the array’s size, its value is immutable.

public class Main
{
  public static void main (String[]args)
  {
    // your code here
    String[]names = new String[3];
    names[0] = "Quincy";
    names[1] = "Abbey";
    names[2] = "Kolade";
  }
}

There are a total of 3 indexes:

  • Quincy is the value at index 0.
  • Abbey is the value at index 1.
  • Kolade’s value is at position 2.

Don’t let the numerals 0, 1, or 2 confuse you. Because arrays are zero-indexed, counting begins at 0 rather than 1.

You would encounter an error in the array above if you attempted to add more information, such as names[3] = “Chris,” as you had specified that the array should only have three items. If you wish to add more values, you must expand the array’s size.

Using the built-in function toString() { [native code] }() method, you may print the array to the console:

System.out.println(Arrays.toString(names));

Also read, Even Disney is Investing in AI: A Look at Face Re-Aging for Visual Effects

Initialize an array in one line

dataType [ ] nameOfArray = {num1, num2, num3, num4}

Using this method there is no need for you to specify the size of the array you can store any amount of objects in it.

Also read, Understanding Java String methods with examples

Different methods associated with Arrays with examples

Traversing through Array

An array can be traversed using a loop. We can print each element one by one, you can retrieve the elements at each index by iterating the for loop from 0 to the length of the array (ArrayName.length).

Example

public class Main
{
  public static void main (String[]args)
  {
    //Creating an array of length 7
    int myArray[] = new int[7];
    
    //Populating the array
      myArray[0] = 1254;
      myArray[1] = 1458;
      myArray[2] = 5687;
      myArray[3] = 1457;
      myArray[4] = 4554;
      myArray[5] = 5445;
      myArray[6] = 7524;
      
     
    //Printing Contents using for loop
    System.out.println ("Contents of the array: ");
    
    for(int i = 0; i < myArray.length; i++){
        System.out.print(myArray[i]+", ");
    }
    
    //1254, 1458, 5687, 1457, 4554, 5445, 7524,
  }
}

Also read, Understanding Java Math Class And its different methods

Adding an element

The Java assignment is to insert element x into an array of size n. Java does not support dynamic changes to array size as C/C++ does. You can add a new element in the given array as:-

  • Initialize the array with the given size n.
  • Using the loop, enter the array at each index.
  • Print the new array.

Example

import java.util.*;
public class Main
{
  public static void main (String[]args)
  {
    Scanner sc = new Scanner (System.in);
    
    System.out.println ("Enter array size");
    int n = sc.nextInt ();

    // Create in Array of size n
    int[] arr = new int[n];

    for (int i = 0; i < n; i++){
    	System.out.println("Enter a element in array");
    	arr[i] = sc.nextInt();
    }
    
    // Printing each element in the array
    System.out.println ("Elments in Array are:-");
    for (int i = 0; i < n; i++){
        System.out.print(arr[i]+", ");
    }

  }
}

Also read, Understanding Java Conditional Statement with Flowcharts

Removing an element

The fundamental strategy entails identifying the element at the given index, then eliminating it. A new array is created with copies of the remaining elements. This would result in an array that was one size smaller than the initial array import java.util.Arrays.

Note- We cannot alter the size of an array, after the removal, the last and second last element in the array will exist twice.

Example

import java.util.Arrays;
public class Main
{
  public static void main (String[]args)
  {
    int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
    
    // Printing orignal array
    System.out.println("Original Array : "+Arrays.toString(my_array));
    
   // Remove the second element (index->1, value->14) of the array
   int removeIndex = 1;

   for(int i = removeIndex; i < my_array.length -1; i++){
       my_array[i] = my_array[i + 1];
   }

    // Printing new array
    System.out.println("After removing the second element: "+Arrays.toString(my_array));
  }
}

Also read, Things you don’t know about the Java Switch statement

Evaluating the total length of the array

With the array, there is no size() method accessible. However, the array has a length field that can be used to determine the length or size of the array.

array.length: The last variable that applies to arrays is length.

Example

public class Main
{
  public static void main (String[]args)
  {
    int[] array = new int[4];
    System.out.println ("The size of " + "the array is " + array.length);
  }
}

Also read, Simple Explanation of Java Loops

Final Words

In other words, we can summarize Array as A container object called an array that carries a predetermined number of values of a single kind. When an array is constructed, its length is predetermined. Its length is fixed once it is created. Earlier, in the main method of the “Hello World!” application, you saw an example of an array. A number is used to access each element in an array, which are collectively referred to as elements. When an array is constructed, its length must be given. A new operator or an array initializer can be used to build an array. Once generated, the size of the array cannot alter. You utilize the length attribute to determine the array’s length. An array’s index can be used to access any element within it. Indices start at 0 and end at the array’s length minus 1.