java

How to initialize an array in Java?

An array is a container object with a fixed number of elements of the same type. Once an array is created, it cannot be resized.
 

Create an empty array

A new empty array with a fixed length is created with the statement type[] name = new Typ[length];. This syntax applies to primitive types as well as to objects:

String[] stringArray = new String[10];

char[] charArray = new char[10];

int[] intArray = new int[10];

float[] floatArray = new float[10];

double[] doubleArray = new double[10];

long[] longArray = new long[10];

boolean[] booleanArray = new boolean[10];

byte[] byteArray = new byte[10];

short[] shortArray = new short[10];
 

Create an array with values

It is also possible to fill an array with values when creating it. This works for primitive types as well as for objects.

String[] names = new String[]{"Alex", "Thomas", "Bob", "Emily"};
int[] numbers = new int[]{1, 2, 3, 4, 5};

As an optimized notation, you can also simply omit the type. But this is only allowed if the declaration of the array and its initialization are in a statement:

String[] names = {"Alex", "Thomas", "Bob", "Emily"};
int[] numbers = {1, 2, 3, 4, 5};

The following code generate an error:

String[] names;
// The following line don't compile !!!
names = {"Alex", "Thomas", "Bob", "Emily"};
// The following line compiles without problems
names = new String[]{"Alex", "Thomas", "Bob", "Emily"};
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *