Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

How do I declare and initialize an array in Java?

1 Answer

0 votes
by (13.1k points)

You can either use array declaration or array literal

For primitive types:

int[] myIntArray = new int[3];

int[] myIntArray = {1, 2, 3};

int[] myIntArray = new int[]{1, 2, 3};

// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html

int [] IntArray = IntStream.range(0, 100).toArray(); // From 0 to 99

int [] IntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100

int [] IntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.

int [] IntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort 

For classes, for example String, it is the same:

String[] StringArray = new String[3];

String[] StringArray = {"x", "y", "z"};

String[] StringArray = new String[]{"x", "y", "z"};

The third way of initializing is useful when you declare an array first and then initialize it, pass an array as a function argument, or return an array. The explicit type is required.

String[] StringArray;

StringArray = new String[]{"x", "y", "z"};

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 7, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...