Arrays in Java

walden systems, geeks corner, programming, languages, java, scope, local scope, global scope, functions, variables, developer, object oriented language, OOP, File, output, stream, fileoutputstream, string, getbyte
Java Powers the Biggest Technology. Mobile. Web apps. The Internet of Things. Big data. Machine learning. Cloud platform and cloud infrastructure. The next big things are here now, and Java is at the center of them all. Whether you’re developing the robust enterprise back end, building the agile front end, or thriving in a DevOps role, Java skills can up your game. With more than 10 million programmers and 13 billion Java-enabled devices worldwide, Java is the language that connects applications to data, data to people, and people to their digital lifestyle.

In programming, an array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. The elements must hold the same data type in Java's implementation of the array. In Python and PHP, the elements can hold different data types. In Java, when creating a new array, the size must also be declared. In other languages such as PHP and Python, the size does not have to be declared. Since the size has to be declared in Java, once an array is created, elements can't be added or deleted from it.

In Java, declaring an array involves 3 steps: declaring the type, declaring the size, and instantiating the array. In Python, there is only one step, declaring the array. Java requires that the elements hold the same data type unlike Python and PHP which allows any data type to be held in the elements. Java also requires that the size of the array to be declared so the size of the array are immutable. In Python and PHP, since the size is not set, we can add or remove elements in an array. Since in Python and PHP, array size can change, they include methods to modify arrays. Finally, in Java, in order to create an array, an array object must be instanced using the "new" keyword. We can combine all three steps involved into creating an array on a single line. Here are some examples of creating arrays in Java, Python and Perl.

Java

    int[] myArray ;

    myArray = new int[2] ;

    // declare, create and instantiate an array on a single line
    int myArray2[] = new int[2] ;


PHP
    $array1 = array(
        1 => "a",
        2 => "b",
    ) ;

    $array2 = array["Mary",2,"lamb");

   $array3 = array(
       "name" => "John",
       "age" => 36,
  ) ;


Python
    array1 = ["a","b","c"]
    array2 = ["Mary", 2, "lamb"]


Array elements are accessed by their index. In Java, the index is an integer value starting at 0 so the first element of an array with 10 elements is 0 and the last element is 9. Python also works this way, array elements are also accessed by an integer index. PHP is different in this context because PHP allows us to use any integer or string as an index. Since the data type and size of the array is defined when creating an array in Java, the array is initialized with default values depending on what the data type is. For anything that holds an object the elements are initialized to null. For int, short, byte and long, the elements are initialized to 0. For float and double, elements are initialized to 0.0. For booleans the elements are initialized to false. For char, it is set to the null character. Python and PHP initializes array to null since no data type or size is needed to create an array. In order to print all the elements in an array, we have to use the for loop or for each loop. In Python and PHP, we can just print the array.

Java

   // Java program to iterate over an array 
   // using for loop 
   import java.io.*; 
   class GFG { 
  
    public static void main(String args[]) throws IOException 
    { 
        int myArr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; 
        int i, x; 
  
        // iterating over an array using for loop
        for (i = 0; i < myArr.length; i++) 
        { 
  
            // accessing each element of array 
            x = myArr[i]; 
            System.out.print(x + " "); 
        } 

        // iterating over an array using for each
        for (int i : myArr) 
        { 
  
            // accessing each element of array 
            x = i; 
            System.out.print(x + " "); 
        } 
    } 
} 



PHP
    $myArr = array("foo" => "bar","bar" => "foo",);
    print_r($myArr) ;


Python
    myArr = ["a","b","c"]
    print myArr

PHP and Python gives us the ability to add or remove elements from an array but Java does not allow this. This makes adding or removing elements from an array more challenging than in Python and PHP. In PHP and Python, it is just a matter of calling a method to remove an element. In Java, it is much more involved, we will use the Scanner library in Java to do this. We can simulate a remove in Java by the following code and setting the last index we access one less than the size of the array. Here is the code :

import java.util.Scanner;

public class removeElem {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] myArr = {1, 2, 4, 5};
        int del_value = 3;
        
        for(int i = 0; i < myArr.length; i++){
            if(intArr[i] == elem){
                // shifting elements
                for(int j = i; j < myArr.length - 1; j++){
                    myArr[j] = myArr[j+1];
                }
                break;
            }
        }
      

        for(int i = 0; i < (intArr.length - 1); i++){
            System.out.print(" " + intArr[i]);
        }                
    }
}

If you are coming from the Python or PHP language, using arrays in Java may seem daunting but if you keep in mind that Java's implementation is nothing more than a collection of objects with certain restrictions, it will be much easier to make the transition. The hardest part of making the transition is the realization that arrays in Java can be resized, keeping the data type the same is a minor annoyance but good programming practice anyway.