1.

Arrays in Java

Answer»

In Java, an array is a collection of like-typed variables with a common name. Arrays in Java are not the same as those in C/C++. The following are some key points to remember regarding Java arrays.


  • All arrays in Java are allocated dynamically. (explained further down)

  • Because arrays are objects in Java, we may use the object attribute length to determine their length. This differs from C/C++, where we use sizeof to find the length.

  • With [] following the data type, a Java array variable can be declared just like any other variable.

  • The array’s variables are sorted, and each has an index starting at 0.

  • An array’s size must be given using an int or short integer rather than a long number.

  • Object is the array type’s direct superclass.

  • Every array type implements the Cloneable and java.io.Serializable interfaces.

Syntax for declaring an array:-

datatype variable_name[];
OR
datatype[] variable_name;

Despite the fact that the above declaration declares variable_name to be an array variable, no actual array exists. It just informs the compiler that this variable (variable_name) will contain an array. You must allocate memory space to it using the new operator.

Syntax of instantiating an array in java:-

variable_name = new datatype [size];

For example,

int sample_array[]; //declaring array
sample_array = new int[20]; // allocating memory for 20 integers to array

Array Literal:-

Array literals can be utilised in situations where the size of the array and its variables are already known.

For example,

int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

The produced array’s length is determined by the length of this sequence. In the most recent versions of Java, there is no need to write the new int[] portion. 




Discussion

No Comment Found