java how to create an array

java how to create an array

To create an array in Java, you can use the new operator followed by the data type of the array elements and the size of the array.

Here is an example of how to create an array of integers with a size of 10:

refer ‮‬to:lautturi.com
int[] array = new int[10];

In this example, the array variable is declared as an array of integers with a size of 10. The new operator is used to create the array and allocate memory for the elements.

You can also use the shortcut syntax to create and initialize an array:

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

In this example, the array variable is declared as an array of integers and initialized with the values 1, 2, 3, 4, and 5.

You can also create an array of objects using the new operator and the class name of the object:

String[] array = new String[5];

In this example, the array variable is declared as an array of strings with a size of 5. The new operator is used to create the array and allocate memory for the elements.

You can access and modify the elements of an array using the array index. For example, to access the third element of the array variable in the above examples, you can use the following syntax:

array[2] // access third element
array[2] = "Hello" // set third element to "Hello"

This will access or set the value of the third element of the array variable.

Note that in Java, array indices start at 0, so the first element of an array is at index 0, the second element is at index 1, and so on.

Created Time:2017-11-03 22:21:12  Author:lautturi