Java create new array
In Java, you can create a new array using the following syntax:
dataType[] newArray = new dataType[arrayLength];
Here, dataType
is the type of the elements in the array, arrayLength
is the number of elements in the array, and newArray
is the name of the array.
For example, to create a new array of integers with 5 elements, you would use:
int[] myArray = new int[5];
This creates a new array of integers with 5 elements, and assigns it to the variable myArray
.
You can also use the new
keyword to create an array of a specific size, like this:
int[] myArray = new int[]{1, 2, 3, 4, 5};
This creates a new array of integers with 5 elements, and initializes it with the values 1, 2, 3, 4, and 5.
Alternatively, you can use the Arrays
class to create a new array, like this:
int[] myArray = Arrays.copyOfRange(new int[0], 0, 5);
This creates a new array of integers with 5 elements, and initializes it with the values 0, 1, 2, 3, and 4.
Note that in Java, arrays are objects, so you can assign them to variables, pass them as arguments to methods, and return them from methods.
Here is an example of how you can create a new array and use it:
public class Main {
public static void main(String[] args) {
int[] myArray = new int[5];
// assign values to the array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;
// print the array
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
}
}
This code creates a new array of integers with 5 elements, assigns values to the array, and then prints the array using a for
loop.