To create an array in Java, you can use the new
operator followed by the type of the array and the size of the array in square brackets. For example, to create an array of integers with 10 elements, you can use the following code:
int[] numbers = new int[10];
This creates a new array called numbers
that can hold 10 integers. The elements of the array are initialized to their default values, which are 0 for integers.
You can also use the new
operator to create an array of objects. For example, to create an array of String
objects with 5 elements, you can use the following code:
String[] strings = new String[5];
This creates a new array called strings
that can hold 5 String
objects. The elements of the array are initialized to null
.
You can also use the short form of the array creation expression, which is an array literal, to create an array. For example, you can create the numbers
array like this:
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
This creates a new array called numbers
with the elements 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.