Java notes: Arrays

Q) What is an array?

An array is a data structure which stores a fixed-size sequential collection of elements of the same data type. Every element in an array is of the same type.

Q) How to declare an array variable?

In order to use an array in a program, a variable to reference the array and the array’s data type is required.

dataType [] arrayReferenceVariable;

or

dataType arrayReferenceVariable []; //correct but not preferred

Note that here no memory is allocated from the array.

At this point, the size of the array is not fixed.

  • Once an array is created, its size is fixed.
  • Unlike the declaration of a primitive data type variable, the declaration of an array variable does not allocate any space in memory for the array. Instead, only a storage location for the reference to an array.
  • If an array variable does not contain a reference to an array, the value of the variable is null.
  • After an array variable is declared, you can create an array by using the new operator and assign its reference to the array variable. By using the new operator memory is allocated for the array.
int [] sampleArray; //declaring an array
sampleArray = new int [10] 
  • In the second line above, the second statement does two things:
    • it creates an array of 10 elements using “new int [10];”
    • it assigns the reference of this array to the variable sampleArray
  • The array sampleArray has 10 elements of int types and indices from 0 to 9
int [] sampleArray = new int [10]; //combining declaration of array variable, creation of array, and assignment of array reference
//to array variable
Q) How to assign value to an element of an array?

arrayRefVar [index] = value;

For example,

sampleArray [3] = 12;

Q) What is the difference between array and array variable?

An array is the continuous memory space that contains values of its elements. The array variable contains the reference to the array.

Q) How can the size of an array be obtained?

arrayRefVar.length;

Q) What are the default values assigned to array elements on creation?

When an array is created, its elements are assigned the default value of 0 for numeric primitive data types, \u0000 for character data types, and false for boolean data type.

Q) How can you access a particular element in an array?

The elements of an array can be accessed through their index. The indices in an array range from 0 to arrayLength-1.

Q) What is array initialization?

An initializer combines declaration, creation, and initialization of an array in one statement

double [] numArray = {23, 32, 1, 4, 45};

Note that the new operator was used to create the array. When you create an array using array initialier, you must make sure to include the declaration, creation, and initialization all in one line. The following would be a syntax error:

double [] numArray;
numArray = {23, 32, 1, 4, 45};

Q) Why are arrays processed using for loops?

Arrays are processed using for loops for two main reasons:

  1. As we know, all the elements in an array are of the same type. Therefore, they can be processed in the same fashion repeatedly using a for loop
  2. We can find the size of an array using the arrayRefVar.length function. Therefore using a loop to traverse the length of a loop is a convenient option.

Q) What is a foreach loop?

The foreach loops enables the user to traverse the array sequentially without having to use an index number. The loop variable should be of the same type as elements in the array.

Syntax:

for (elementType loopVar: arrayReferenceVariable){
}

For instance,

int [] num= {1,2,3,4,5}

for (int i : num){
System.out.println(i);
}

A foreach look can be read as “for each element i in num, do the following”

Q) What is the ArrayOutOfBoundsException? How can you avoid it?

When the index of the array reaches beyond its fixed size during runtime, the ArrayOutOfBoundsException is thrown.

Ensure that the index does not go beyond arrayRefVar.length-1 or simply use a foreach loop.

Q) What is off-by-one error?

When a programmer makes the error of assuming that the index of an array begins from 1 (and not 0).

Another off by one error arises when the programmer makes the following mistake.

for (int i=0; i<=array.length; i++){
}

Notice that the programmer has used <= instead of <.

Q) How can you copy one array to another?

Individual elements of the array have to copied to the new array.

Note that arrayVar1= arrayVar2 does not copy the elements of one array to the other. Using the statement only copies the reference one array to the other. So the two arrayRefVariables will point to the same array.

There are three ways to copy one array to another:


1. Using a loop to copy each element of array1 to array2

for (int i=0; i<array1.length; i++){
array2[i]= array1[i];
}


2. Using the static arraycopy function in the java.lang.System class

Syntax:
System.arraycopy(sourceArray, sourceStartingPos, targetArray, targetStartingPos, length);

Note that the target array must be declared prior to passing it to the arraycopy method. The targetArray created by the arraycopy method does not share the same reference with the sourceArray as the new array has an independent memory location.


3. Using clone class function.

Q) What is garbage collection?

Suppose you have two array reference variables arrayRef1 and arrayRef2. Both point to array1 and array 2 respectively. Now if we add the statement arrayRef2= arrayRef1, arrayRef2 no longer points to array two but instead point to where arrayRef1 is pointing i.e array1. The array that arrayRef2 previously pointed to (array2) is no longer referenced and is considered ‘garbage.’ The Java Virtual Machine automatically clears the garbage from the memory. This is known as garbage collection.

Q) Give the syntax of passing an array to a method.

Syntax:
public void sampleMethod (int [] array){
}

Remember that the reference of the array is passed to the method. So any changes made to the array in the method, will be reflected in the original array.

Q) What is an anonymous array?

printArray(new int [] {1,2,3,4,5});

The above array being passed to the printArray method is an anonymous array. There is no explicit reference variable of the array.

  • pass-by-value is used when a primitive data type is passed to a method
  • pass-by-reference is used when an array is passed to a method
  • Arrays are objects in Java. The JVM stores objects in an area of memory called heap, which is used for dynamic memory allocation.
Q) Give the syntax of returning an array from a method.

public static int[] returnArray (int [] array){
int [] newArray= new int[array.length];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}

When a method returns an array, it returns the reference of the array.

Q) What are Variable-Length Argument Lists (VarArgs) in Java?

A variable number of arguments of the same type can be passed to a method and treated as an array.

Syntax:
type… varName

Only one variable-length parameter can be declared in a specific method.

Also, return type of a method cannot be a varargs type

package Array;

/**
 * Created by aarushi on 1/5/21.
 */
public class ArrayVarArgsSample {

    //method takes variable number of integer arguments
    public static void varargsSample (int ... sample){
        for(int i=0; i<sample.length; i++){
            System.out.print(sample[i]+ " ");
        }
        System.out.println();
    }

    public static void main (String [] args){
        varargsSample(1, 2 , 3, 4);
        varargsSample(new int[] {2,4});
        varargsSample(0);
    }
}
Q) Why is Linear Search less efficient as compared to Binary Search?

The execution time of linear search algorithm increases in proportion with size of the array.

Q) What is the java.util.Arrays class?

The java.util.Arrays class contains several static methods which are used to carry out common array operations like searching, sorting, comparing, filling array elements, and return a strinf representation of an array.

  • The main method can receive String commands from the command line
  • In the header of the main method, we write:
    public static void main (String [] args)
    So from the arguments in the header parenthesis, we can conclude that args is the reference variable to of array of strings
  • When the main method is invoked, the Java interpreter creates an array to hold command line arguments and passes the array reference to args.

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.