Array index length java

How to declare and initialize arrays in java

What is Java Array?
An array is a group of elements of similar data type.
Array elements can be either primitives(such as int , float , double ) or objects(such as String, Person, Dog etc.).
Array itself is an object irrespective of its element types and is stored on the heap.

If an array contains primitive elements, it should be called an array of primitives but it is incorrect to say primitive array as there is no such thing as primitive array.

Array declaration
An array in java can hold elements of only one type. Thus, it is declared by stating the type of elements that it will contain.
Type should be followed by square brackets and a user defined name of the variable that will represent the array.
Following examples declare an array of int , double , string , char , objects etc.

//array of int int[] integers; // array of double double [] numbers; //recommended double numbers[]; // allowed but not recommended // array of objects Dog[] dogs;

//array of int int[] integers; // array of double double [] numbers; //recommended double numbers[]; // allowed but not recommended // array of objects Dog[] dogs;

It is not permitted to provide the size of array at the time of declaration and will raise a compiler error.
This is because memory is not allocated for the array till it is created.
Initialize array
Till now we only declared the array which tells JVM about the type of elements the array will contain.
Defining or initializing an array means actually constructing the array where we specify the size of the array(number of elements in the array) so that JVM can allocate memory for it.

Читайте также:  Поиск натурального делителя питон

An array can be created in two ways:
1. Using new array
Create array just like an object is created using new operator. Example,

// create array of five integers int[] numbers = new int[5]; // create array of five dog objects Dog[] dogs = new Dog[5];

// create array of five integers int[] numbers = new int[5]; // create array of five dog objects Dog[] dogs = new Dog[5];

It is not possible to change the size of array after it is created. You can not increase or decrease the number of elements that an array can hold after it is created.

2. Direct initialization
Provide elements right at the time of declaration. You do not need to provide the size when using this method since it is calculated by the number of elements given while initialization.
Also, elements of the array are provided within curly braces.
Example,

// create an array of 6 elements int[] numbers = {2, 3, 45, 6, 7, 8}; // create array of 2 dog objects Dog[] dogs = {new Dog("a"), new Dog("b")};

// create an array of 6 elements int[] numbers = ; // create array of 2 dog objects Dog[] dogs = ;

It is also possible to split array declaration and initialization in two different statements as shown below.

int[] numbers; // declare int array numbers = new int[5]; // create an array of 5 elements

int[] numbers; // declare int array numbers = new int[5]; // create an array of 5 elements

This is usually done when the size of the array at the time of declaration is not known.
But you can not do this when directly initializing array elements.
That is, following will invite a compiler error.

int[] numbers; // declare array numbers = {2, 3, 45, 6, 7, 8}; // NOT allowed

int[] numbers; // declare array numbers = ; // NOT allowed

representation of array of primitive elements

Array memory representation
An array is an object and objects in java are stored on heap memory.
Thus, an array of primitive elements(such as integer) will be stored as shown below.
An array whose elements are themselves objects is represented as below.

representation of array of objects

Default values of elements of an integer array is 0 while all elements of an object array will be initialized to null after the array is created but no elements are assigned to it.

Accessing Array elements
Array elements are index based with index starting from 0 to length of array – 1.
That is, for an array of five elements, its index will range from 0 to 4 with index of first element being 0, second element 1 and last element 3.
For accessing an array element, its index is used. Syntax to access an individual array element is by using the name of array reference variable followed by its index in square brackets.
Thus, for an array of 5 elements,

numbers[1] will return the second array element
numbers[0] will return the first array element
numbers[4] will return the last array element

If you try to access array index which is outside the length of array, then a java.lang.ArrayIndexOutOfBoundsException is raised.
Example, for an array of length 5, accessing indexes above 4 and below 0 will raise this exception.

Array length
Length or size of array is the total number of elements in the array and can be found using its length property.
Remember the index of array elements will be from 0 to length – 1. Example,

// initialize array of strings String[] colors = {"Violet", "Blue", "White", "Black"}; System.out.println(colors.length); // will print 4

// initialize array of strings String[] colors = ; System.out.println(colors.length); // will print 4

Loop over array
Since an array is a collection of elements, it can be iterated over by a loop.
This loop can be a normal loop which uses index based iteration such as for or while loop or enhanced for loop(also referred as for-each loop).
Index based looping
This approach initializes a for loop from 0 till length of array – 1. In every iteration, you can access the current array element using its index. Example,

int[] numbers = {23, 45, 62, 1}; // length is 4 // loop from 0 till 3 for(int index = 0; index  numbers.length - 1; index++) { System.out.println("Element at position " + index + " is " + numbers[index]); }

int[] numbers = ; // length is 4 // loop from 0 till 3 for(int index = 0; index

Element at position 0 is 23
Element at position 1 is 45
Element at position 2 is 62
Element at position 3 is 1

Array foreach
This approach does not use indexing. Instead, it uses a variable which is of the same type as the array.
In every iteration, this variable contains the current array element.
This is called for-each loop or enhanced for loop in java .
Example,

// initialize array of strings String[] languages = {"java", "python", "C#"}; System.out.println("Languages are: "); // loop with foreach for(String lang: languages) { System.out.println(lang); }

// initialize array of strings String[] languages = ; System.out.println(«Languages are: «); // loop with foreach for(String lang: languages)

Notice the use of colon( : ) after variable name. Above code outputs

Languages are:
java
python
C#

Modifying Array elements
Elements of an array can be modified after its creation using assignment operator(=) and the element index.
Assign a new value to the element which needs to be modified using its index as shown below.

String[] fruits = {"Apple", "Banana", "Orange", "Grapes"}; fruits[1] = "Papaya"; // replace Banana with Papaya

String[] fruits = ; fruits[1] = «Papaya»; // replace Banana with Papaya

Assigning elements to array using a loop
It is also possible to initialize array elements after its creation using a loop and assignment operator. This can only be done using index based loop and not using enhanced for loop. Example,

// create an array of 4 elements int[] numbers = new int[4]; // loop from 0 till 3 for(int index = 0; index  numbers.length - 1; index++) { // assign element to current position numbers[index] = index * 10; }

// create an array of 4 elements int[] numbers = new int[4]; // loop from 0 till 3 for(int index = 0; index < numbers.length - 1; index++) < // assign element to current position numbers[index] = index * 10; >

Two dimensional array example

Multidimensional arrays
All the arrays demonstrated till now are one dimensional arrays. A one dimensional array contains a single element at each array location.
Type of this element is the same as that of the array.
If an array element is another array, then such array is called a multidimensional array in java.
A multidimensional array is represented as below.

Above is an example of a two dimensional int array where element at every array index is another int array.
Note that if a the main array index does not point to another array, then it is initialized as null.
Initializing multidimensional arrays
A multidimensional array is created using multiple square brackets, one for each dimension. Example,

// create a two dimensional array int[][] numbers = new int[4][4]; // create a one dimensional array int[] arrayOne = new int[4]; // create another one dimensional array int[] arrayTwo = new int[4]; // assign elements of two dimensional array numbers[0] = arrayOne; numbers[1] = arrayTwo;

// create a two dimensional array int[][] numbers = new int[4][4]; // create a one dimensional array int[] arrayOne = new int[4]; // create another one dimensional array int[] arrayTwo = new int[4]; // assign elements of two dimensional array numbers[0] = arrayOne; numbers[1] = arrayTwo;

Above example creates initializes a two dimensional or double dimensional int array. Each element of this array is another array.
Note that it is created using double square brackets.
First bracket indicates the number of elements in the main array and second bracket indicates the number of elements in element array .
Default array values
After the array is declared and initialized but its elements are not given any values, they have a default value. The default value depends on the type of array.
Below table summarizes the default values of array elements.

Array Type >Default Element Value
int 0
float 0.0
double 0.0
boolean false
object null

Print array
An array is an object in java. If you directly print an array using System.out.print , then it will not print its element.
In order to print an array to show meaningful information, you need to take some special measures.
Refer this article to learn how to print a java array in the required format.

Click the clap if the article was useful for you.

Источник

Class Array

Array permits widening conversions to occur during a get or set operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

Method Summary

Sets the value of the indexed component of the specified array object to the specified boolean value.

Methods declared in class java.lang.Object

Method Details

newInstance

Creates a new array with the specified component type and length. Invoking this method is equivalent to creating an array as follows:

int[] x = ; Array.newInstance(componentType, x);

newInstance

Creates a new array with the specified component type and dimensions. If componentType represents a non-array class or interface, the new array has dimensions.length dimensions and componentType as its component type. If componentType represents an array class, the number of dimensions of the new array is equal to the sum of dimensions.length and the number of dimensions of componentType . In this case, the component type of the new array is the component type of componentType . The number of dimensions of the new array must not exceed 255.

getLength

get

Returns the value of the indexed component in the specified array object. The value is automatically wrapped in an object if it has a primitive type.

getBoolean

getByte

getChar

getShort

getInt

getLong

getFloat

getDouble

set

Sets the value of the indexed component of the specified array object to the specified new value. The new value is first automatically unwrapped if the array has a primitive component type.

setBoolean

public static void setBoolean (Object array, int index, boolean z) throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Sets the value of the indexed component of the specified array object to the specified boolean value.

setByte

setChar

setShort

setInt

setLong

setFloat

setDouble

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Оцените статью