That's probably one of the most popular topics about programming and software engineering. Arrays are used in many software applications. That is the core functionality of almost any programming language. As a result, it's very important for any developer to know how to correctly work with the arrays.
Java language allows you to declare and initialize arrays in many different ways. This tutorial may be a good place to learn how to properly create arrays in your code.
Table of Contents
- Declaring an array in Java
- Declaring a multidimensional array
- Allocating memory for array
- Initializing an array in Java
- Allocating memory for an array of objects in Java
- Initializing an array of objects in Java
- How to access single element of an array
- How to get length of an array
- How to use mixed data types in array
- Allocating memory for multidimensional array
- Initializing a multidimensional array
- Initializing a ragged array
- Using the loop to initialize the array
- Using the loop to initialize multidimensional array
- Using the IntStream.range() method
- Using the IntStream.rangeClosed() method
- Using the IntStream.of() method
- Example of using reflections in Java
- Creating an array with random values
- Using the Arrays.fill() method
- Using the Arrays.setAll() method
- Using the and takeWhile() methods
- Using the Arrays.copyOf() method
- How to clone an array
- How to clone a multidimensional array
- Passing an array into a function
- Returning an array from a function
- Using the ArrayList class
- Using the Arrays.asList method
- Conclusion
Declaring an array in Java
It's very easy to declare an array in Java. You just need to specify the type of the data, give the name of the array and append the [] value to the declaration.
Below are the options that you can use in your code. It's possible to append the [] specification either after the type or after the name of the array.
ARRAY_DATA_TYPE NAME_OF_YOUR_ARRAY[];
ARRAY_DATA_TYPE[] NAME_OF_YOUR_ARRAY;
Now, it's time to see some examples. Following are the defections for the very basic arrays of different types, such as int, byte, short and so on. As you see, the square brackets are added after the name of the array.
int intData[];
byte byteData[];
short shortData[];
boolean booleanData[];
long longData[];
float floatData[];
double doubleData[];
char charData[];
Also, you can choose to use the other method of declaring an array. Below, you can see the other definition. Square brackets are placed after the type of array.
int[] intData;
byte[] byteData;
short[] shortData;
boolean[] booleanData;
long[] longData;
float[] floatData;
double[] doubleData;
char[] charData;
Java also allows you to create an array of objects. The declaration is exactly the same as for native types of data. But instead of a built-in type, you have to provide the name of the desired class. In addition, it is possible to place square brackets either after the name of the array or after the class name. The specification is shown below.
YourCustomClass arrayName[];
YourCustomClass[] arrayName;
Following is an example of how to define an array of objects.
Object yourObjectData[];
Also, you may put the square brackets after the Object class, see it below.
Object[] yourObjectData;
Declaring a multidimensional array
Multidimensional array is an array that contains other arrays inside of every element of the parent array. In other words, that's a table of tables. Java handles the multidimensional arrays very well and it's easy to create them. Below, you can see the specification.
ARRAY_DATA_TYPE NAME_OF_YOUR_ARRAY[][];
ARRAY_DATA_TYPE[][] NAME_OF_YOUR_ARRAY;
You can use any option that you wish. The same as for single dimensional arrays, the square brackets may be placed either after the name of the array or after the data type.
The interesting thing is that you are not limited to just 2-dimensional arrays. You can create even 3 or 4 dimensional arrays. You just have to add another pair of square brackets to the array definition. See our examples below. Both types of definitions will work with the multi-level array.
ARRAY_DATA_TYPE NAME_OF_YOUR_ARRAY[][][];
ARRAY_DATA_TYPE[][][] NAME_OF_YOUR_ARRAY;
Following is an example of a very simple 2-dimensional array that contains integer numbers only.
int intData[][];
Also, you may place the square brackets right after the data type, like it's shown below.
int[][] intData;
In addition, we provide an example of the 3-dimensional array, just in case you want to use it. Below see code for both types of definitions.
int intData[][][];
int[][][] intData;
Allocating memory for array
Following is the specification of how the memory should be allocated for the array. As you may see, we use the new operator there, which allows you to create a desired array. Also, you have to specify data type and size in your code.
ARRAY_DATA_TYPE[] NAME_OF_ARRAY = new ARRAY_DATA_TYPE[SIZE_OF_ARRAY];
Below you can see examples of how the float and integer arrays are created in Java. Each array may hold 10 values. The indexes are from 0 and up to 9 inclusive.
int[] intData = new int[10];
float[] floatData = new float[10];
Also, we provide you a very basic example that shows how to create the array. You may try to run that code.
import java.lang.reflect.Array;
import java.util.Arrays;
class sample {
public static void main(String args[]) {
int[] intData = new int[10];
System.out.println(Arrays.toString(intData));
}
}
This application will output zeros to the console, since we haven't initialized the array with the data.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Initializing an array in Java
The simplest way to initialize the array is to assign specific values to the element at a given index. See the example below.
intData[0] = 1;
intData[1] = 2;
intData[2] = 3;
However, this method is not convenient. It may not be acceptable if the arrays are large. There are other methods available in Java that allow you to fill the array with data. Please review the following sections of this tutorial.
Standard method of initializing the array with data
The array may be initialized at the same time it's created. To do that, you may provide a list of comma separated values in curly braces. See example of how to make an array of integers.
int intData[] = new int[]{1, 2, 3, 4, 5, 6 ,7, 8, 9, 10};
Below, you can also see how the array of strings is initialized.
String[] stringData = new String[]{"red", "green", "blue"};
Short method of initializing the array with data
Also, there is a short method of initializing the array. You don't have to use the new keyword in that case. The data can be specified directly in curly braces. The size of the array is determined from the number of elements that you give. See below example of how it can be done.
int intData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
The above code creates an array of integers. The same way, you can create an array of string values, see it below.
String[] stringData = {"red", "green", "blue"};
Returning array from the function
You may also declare and initialize some array inside of a function. Then, that array may be returned to the parent function. However, the array must be created with help of the new keyword, as it's shown below.
import java.lang.reflect.Array;
import java.util.Arrays;
class sample {
public static String[] getColors() {
return new String[]{"red", "green", "blue"};
}
public static void main(String args[]) {
System.out.println(Arrays.toString(sample.getColors()));
}
}
Now, you may try to run our code. The console output will contain a comma separated list of colors.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[red, green, blue]
It's important to note that Java will produce an error if the short syntax is used to return the array from the function. Following code shows the incorrect way of creating an array.
import java.lang.reflect.Array;
import java.util.Arrays;
class sample {
public static String[] getColors() {
return {"red", "green", "blue"};
}
public static void main(String args[]) {
System.out.println(Arrays.toString(sample.getColors()));
}
}
If you try to run the given code, there should be an error like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
./sample.java:6: error: illegal start of expression
Allocating memory for an array of objects in Java
If you need to allocate memory for an array of objects, then it's not an issue. You should do it exactly the same as you would allocate memory for the native Java data types. Below you can see our example.
Apple[] apples = new Apple[5];
Also, we've created a demo that shows how the allocated array of objects behaves during the runtime. The full source code is given below.
import java.util.Arrays;
class Apple {
private int weight = 0;
public Apple(int weight) {
this.weight = weight;
}
public int getWeight() {
return this.weight;
}
@Override
public String toString() {
return Integer.toString(this.weight);
}
}
class sample {
public static void main(String args[]) {
Apple[] apples = new Apple[5];
System.out.println(Arrays.toString(apples));
}
}
If you run the given code, there should be null values in the terminal. That's because the array is not initialized.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[null, null, null, null, null]
Initializing an array of objects in Java
The following code shows how to initialize an array of objects. We create an instance of the Apple class and assign it to the specific element of an array.
import java.util.Arrays;
class Apple {
private int weight = 0;
public Apple(int weight) {
this.weight = weight;
}
public int getWeight() {
return this.weight;
}
@Override
public String toString() {
return Integer.toString(this.weight);
}
}
class sample {
public static void main(String args[]) {
Apple[] apples = new Apple[5];
apples[0] = new Apple(10);
apples[1] = new Apple(20);
apples[2] = new Apple(30);
apples[3] = new Apple(40);
apples[4] = new Apple(50);
System.out.println(Arrays.toString(apples));
}
}
Now, the application should show some data in the terminal.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[10, 20, 30, 40, 50]
Optionally, you may create instances of the Apple class and initialize the array inside of the curly braces, as it's shown below.
import java.util.Arrays;
class Apple {
private int weight = 0;
public Apple(int weight) {
this.weight = weight;
}
public int getWeight() {
return this.weight;
}
@Override
public String toString() {
return Integer.toString(this.weight);
}
}
class sample {
public static void main(String args[]) {
Apple[] apples = new Apple[] {
new Apple(10),
new Apple(20),
new Apple(30),
new Apple(40),
new Apple(50)
};
System.out.println(Arrays.toString(apples));
}
}
The result would be exactly the same as in the previous demo. There should be a list of numbers in the terminal.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[10, 20, 30, 40, 50]
How to access single element of an array
To get a single element from an array, you have to use the square brackets. The index of the desired element should be placed inside of those brackets. The following application takes the first element from an array and prints it to the screen.
class sample {
public static void main(String args[]) {
String[] colors = {"red", "green", "blue"};
System.out.println(colors[0]);
}
}
The console output will be like the following:
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
red
How to get length of an array
There may be a case when the array was created dynamically and you don't know the size of it. Or probably the array was returned from some other function. Also, you may not know the size of the array because of some other reasons.
To solve this issue, you may use the length property. It contains a number of elements that are stored in the array. See the following code sample that shows how to use it.
class sample {
public static void main(String args[]) {
String[] colors = {"red", "green", "blue"};
System.out.println(colors.length);
}
}
If you run the given code, it should print the number 3 to the console.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
3
How to use mixed data types in array
There is a nice feature available in Java. You may use the mixed data types in arrays. It means that the array can hold, for example, integer and string values at the same time. Example is given below.
import java.util.Arrays;
class sample {
public static void main(String args[]) {
Object[] mixedData = {"red", 25, "green", 78, 93, "blue"};
System.out.println(Arrays.toString(mixedData));
}
}
The above application should produce output like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[red, 25, green, 78, 93, blue]
Allocating memory for multidimensional array
It's easy to allocate memory for a multidimensional array. You would do it almost the same as you would initialize the single dimensional array. You only have to add additional square brackets and specify the size of the inner array. Please see the following example to see how it has to be done correctly for the 2-dimensional array.
int[][] intData = new int[10][10];
Also, following is example of how to allocate memory for 3-dimensional array
int[][][] intData = new int[10][10][10];
Initializing a multidimensional array
The easiest way to initialize a multidimensional array is to simply assign a value to each element of an array. However, you also have to use additional brackets. See below how we assign values to the 2-dimensional array.
intData[0][0] = 1;
intData[0][1] = 2;
intData[1][0] = 3;
intData[1][1] = 4;
Also, you may assign values to 3-dimensional array in a similar way:
intData[0][0][0] = 1;
intData[0][0][1] = 2;
intData[0][1][0] = 3;
intData[0][1][1] = 4;
intData[1][0][0] = 5;
intData[1][0][1] = 6;
intData[1][1][0] = 7;
intData[1][1][1] = 8;
Sometimes, it may not be convenient to manually assign each value to a multidimensional array. In that case, you can assign values at the time when you allocate a memory. Following is example of how to do it for a 2-dimensional array:
int[][] intData = new int[][]{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}};
The same way, you can do it for a 3-dimensional array.
int[][][] intData = new int[][][]{
{{1, 2}, {3, 4}, {5, 6}},
{{7, 8}, {9, 10}, {11, 12}},
{{13, 14}, {15, 16}, {17, 18}}
};
The short method of initializing arrays can also be used for creating arrays. Below, you can see how it can be done for a 2-dimensional array.
int[][] intData = {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}};
The next sample shows how it can be done for a 3-dimensional array.
int[][][] intData = {
{{1, 2}, {3, 4}, {5, 6}},
{{7, 8}, {9, 10}, {11, 12}},
{{13, 14}, {15, 16}, {17, 18}}
};
Initializing a ragged array
As you know, all nested arrays at the same level are all of the same size. That's the classical multidimensional array. However, Java language also allows you to create a so-called "ragged" array. It means that the nested arrays may be of a different size. Following is an example of how to allocate memory for such an array.
int[][] intData = new int[3][];
intData[0] = new int[1];
intData[1] = new int[3];
intData[2] = new int[2];
Also, the ragged array can be created and initialized at the same time. See the following code to learn how to do it.
int[][] intData = {{7}, {5, 7, 3}, {5, 3}};
Using the loop to initialize the array
If the array is large, then you may initialize it with help of the for loop. You may assign value to each element of an array in each iteration of the loop. Following is the demo that shows how it may be implemented correctly. Please pay attention that we use the length property there to determine the size of the array.
int[] intData = new int[5];
for (int i = 0; i < intData.length; i++) {
intData[i] = i;
}
You may also initialize an array of objects. The code would be very similar to the previous demo. However, on each iteration, you also have to create an instance of the relevant object.
Object[] objectData = new Object[5];
for (int i = 0; i < objectData.length; i++) {
objectData[i] = new Object();
}
Using the loop to initialize multidimensional array
You may also use the loop to initialize the multidimensional array. But the difference with single dimensional arrays is that you have to use multiple for loops. There should be a separate loop for each dimension. Please see the following code sample. There, we initialize a 2-dimensional array.
int[][] intData = new int[3][5];
for (int i = 0; i < intData.length; i++) {
for (int j = 0; j < intData[i].length; j++) {
intData[i][j] = i + j;
}
}
The same way, you may initialize a multidimensional array of objects. The code sample is given below.
Object[][] objectData = new Object[3][5];
for (int i = 0; i < objectData.length; i++) {
for (int j = 0; j < objectData[i].length; j++) {
objectData[i][j] = new Object();
}
}
Using the IntStream.range() method
Java language provides various helpful methods that can initialize arrays for you. For example, the IntStream.range() method creates an array with a sequence of numbers incremented by one. The first parameter of that method specifies the first value. The last parameter specifies the maximum value, but it's exclusive and will not be included in the array. Now you can see how the code may look:
import java.util.Arrays;
import java.util.stream.IntStream;
class sample {
public static void main(String args[]) {
int[] intData = IntStream.range(0, 5).toArray();
System.out.println(Arrays.toString(intData));
}
}
You may try to run our code, the console output should be like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[0, 1, 2, 3, 4]
Using the IntStream.rangeClosed() method
The IntStream.rangeClosed() method is very similar to the IntStream.range(). But, the difference is that the second parameter to that method specifies a maximum value that is included in the array. In other words, the array will be created with both minimum and maximum values which are inclusive.
import java.util.Arrays;
import java.util.stream.IntStream;
class sample {
public static void main(String args[]) {
int[] intData = IntStream.rangeClosed(0, 5).toArray();
System.out.println(Arrays.toString(intData));
}
}
Please see output of the given code below. As you may see, the number 5 was added to the array.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[0, 1, 2, 3, 4, 5]
Using the IntStream.of() method
The IntStream.of() method creates a stream with the given values. However, that stream can be converted to an array with help of the toArray() method. This means that the IntStream.of() method can also be used to initialize an array. See the code sample below.
import java.util.Arrays;
import java.util.stream.IntStream;
class sample {
public static void main(String args[]) {
int[] intData = IntStream.of(23, 17, 19, 28, 15).toArray();
System.out.println(Arrays.toString(intData));
}
}
This application should produce output like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[23, 17, 19, 28, 15]
If that's needed, you may also sort the data. For that purpose, you may use the sorted() method. See below how exactly it should be called.
import java.util.Arrays;
import java.util.stream.IntStream;
class sample {
public static void main(String args[]) {
int[] intData = IntStream.of(23, 17, 19, 28, 15).sorted().toArray();
System.out.println(Arrays.toString(intData));
}
}
Now, let's see how the given code works. If you run it, it may print values like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[15, 17, 19, 23, 28]
Example of using reflections in Java
You may also use the Array.newInstance() method to create a new array. However, you have also to specify the type of data. Please see the given sample, it shows how this method should be used in application.
import java.lang.reflect.Array;
import java.util.Arrays;
class sample {
public static void main(String args[]) {
int[] intData = (int[]) Array.newInstance(int.class, 5);
System.out.println(Arrays.toString(intData));
}
}
The given code should print a list of zeros to the console, as it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[0, 0, 0, 0, 0]
Creating an array with random values
Java allows you to generate an array that contains random data. It may be very useful, since you don't need to manually assign a random value to each element of your array. For example, this can be done with help of the Random.ints() method. Our code sample is given below. Please pay attention that we use the toArray() method there to convert stream to array.
import java.util.Arrays;
import java.util.Random;
class sample {
public static void main(String args[]) {
int[] intData = new Random().ints(5, -5, 5).toArray();
System.out.println(Arrays.toString(intData));
}
}
It's important to note that the Random class contains many other methods that may return a stream of random values. We recommend you to read the official Java documentation to see all possible options.
Now, you can try to run our code. The console output may be like the following.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[4, -2, 4, 0, -2]
Using the Arrays.fill() method
There is another helpful method in Java that you can use to initialize arrays. The Arrays.fill() method allows you to fill a specific array with a predefined value. In other words, the same value will be assigned to the element of the array. See the example below.
import java.util.Arrays;
class sample {
public static void main(String args[]) {
int[] intData = new int[5];
Arrays.fill(intData, 777);
System.out.println(Arrays.toString(intData));
}
}
Please run the given code, you'll see that the array contains exactly the same number in each element.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[777, 777, 777, 777, 777]
Using the Arrays.setAll() method
You may use generators in Java to fill the array with the data. That is possible with the help of Arrays.setAll() method. To show how it works, we've made a very simple demo. You can see it below. The array is filled with numbers in a range of 0..9.
import java.util.Arrays;
class sample {
public static void main(String args[]) {
int[] intData = new int[10];
Arrays.setAll(intData, value -> value);
System.out.println(Arrays.toString(intData));
}
}
The given code should produce output like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
However, that's a very basic usage of the Arrays.setAll() method. Of course, you can write a more complex generator that may produce a different sequence of numbers.
Using the and takeWhile() methods
Java has the iterate() method that may also be used to produce arrays. It's very interesting since it allows us to use a special function to generate a stream of elements. Then, that stream can be converted to the array with help of the toArray() method. Now, please review the following code. You can see there how to create an array with elements in a range of 0..4.
import java.util.Arrays;
import java.util.stream.IntStream;
class sample {
public static void main(String args[]) {
int[] intData =
IntStream.iterate(0, value -> value < 5, x -> x + 1).toArray();
System.out.println(Arrays.toString(intData));
}
}
If the given code is executed, you should see output like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[0, 1, 2, 3, 4]
You may also use the takeWhile() method to specify a rule that is applied to the given stream. You will get only elements that pass the test. The code is given below.
import java.util.Arrays;
import java.util.stream.IntStream;
class sample {
public static void main(String args[]) {
int[] intData =
IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 5).toArray();
System.out.println(Arrays.toString(intData));
}
}
Our code will produce output in the console like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[0, 1, 2, 3, 4]
Using the Arrays.copyOf() method
If you need to create a copy of an existing array, then Java will also help you. In that case, you may use the Arrays.copyOf() method. Also, you have to know that this method performs a shallow copy of the data.
Now, you can see a code that creates a duplicate of the given array.
import java.util.Arrays;
class sample {
public static void main(String args[]) {
int intData[] = {1, 2, 3, 4, 5};
int[] intDataCopy = Arrays.copyOf(intData, intData.length);
System.out.println(Arrays.toString(intDataCopy));
}
}
If you run our application, you should see a list of numbers in a range of 1..5. Those are the same numbers that are stored in the original array.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[1, 2, 3, 4, 5]
How to clone an array
You may also use the clone() method to make a duplicate of an existing array. The usage is very simple, you don't need to pass any additional arguments. That method returns another array that you may use in your code. It is worth mentioning that this method also makes a shallow copy of the data.
Also, see the following demo that shows how it can be done in an application.
import java.util.Arrays;
class sample {
public static void main(String args[]) {
int intData[] = {1, 2, 3, 4, 5};
int intDataCloned[] = intData.clone();
System.out.println(Arrays.toString(intDataCloned));
}
}
Also, our code should produce output like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[1, 2, 3, 4, 5]
How to clone a multidimensional array
It's also possible to clone a multidimensional array in Java. To do that, you may use the clone() method. It works the same as it is described in the previous section of this tutorial. Now, please review the following code. There, we create a simple multidimensional array. Then, we clone it and print to the terminal.
import java.util.Arrays;
class sample {
public static void main(String args[]) {
int intData[][] = {{1, 2}, {3, 4}, {5, 6}};
int intDataCloned[][] = intData.clone();
System.out.println(Arrays.deepToString(intDataCloned));
}
}
The given code should produce output like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[[1, 2], [3, 4], [5, 6]]
Passing an array into a function
You may pass an array into any function the same as you would do it with other data types. The following code shows how it can be done. We've created a MyTools class that contains the elementExists() method. It can be used to check if some element exists inside of the given array.
class MyTools {
public static boolean elementExists(String[] values, String key) {
int i = 0;
for (i = 0; i < values.length; ++i) {
if (values[i].equals(key)) {
return true;
}
}
return false;
}
}
class sample {
public static void main(String args[]) {
String[] colors = {"red", "green", "blue"};
System.out.println(MyTools.elementExists(colors, "green"));
System.out.println(MyTools.elementExists(colors, "pink"));
}
}
Now, please try to run our code. You should see true and false values on the screen.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
true
false
Returning an array from a function
The following sample shows how to create and return an array from a function. The MyTools class contains the getFavoriteColors() method that returns a list of color names. Then, that array is converted to string and printed to the console.
import java.util.Arrays;
class MyTools {
public static String[] getFavoriteColors() {
return new String[]{"red", "green", "blue"};
}
}
class sample {
public static void main(String args[]) {
System.out.println(Arrays.toString(MyTools.getFavoriteColors()));
}
}
Please try to run the given code. The output should be like it's shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[red, green, blue]
Using the ArrayList class
You may also use the lists in Java applications. They work a bit differently than the regular arrays. However, you may find that lists are more suitable in specific cases. In the following code, we show how to create a simple list that contains three words.
import java.util.ArrayList;
import java.util.List;
class sample {
public static void main(String args[]) {
List<String> colors = new ArrayList<String>();
colors.add("red");
colors.add("green");
colors.add("blue");
System.out.println(colors);
}
}
Our sample should print color names to the console. The output is shown below.
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[red, green, blue]
Using the Arrays.asList method
You may also use the Arrays.asList() method to create a list in Java. The usage of this method is very simple. Below, you can see our code sample. The same as in the previous section of this tutorial, we create a list of color names and print it to the terminal.
import java.util.Arrays;
import java.util.List;
class sample {
public static void main(String args[]) {
List<String> colors = Arrays.asList("red", "green", "blue");
System.out.println(colors);
}
}
If you run the given application, the console output may be like the following:
developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[red, green, blue]
Conclusion
As you see in this tutorial, Java language has a very good support for arrays. Software developers should know how to properly work with them, since that's a very widely used functionality. Arrays are very often used to store and process various types of data.
However, this tutorial covers only the most popular topics. As a result, we strongly recommend reading the official Java guides to get a deeper knowledge on Java arrays and lists.
Comments