How to declare a String array in java

In this post, we will see how to declare String array in java.

Declare String array in java

There are 2 ways to declare String array in java.

Declaring a String array without size

In this declaration, a String array is declared as any normal variable without size. Before using this array, you need to instantiate it otherwise you might get variable might not have initialized error.

Declaring a String array with size

In this declaration, a String array is declared and instantiated at the same time. You can directly use this array, but you will see that myStrArr contains null values as it is not initialized yet.

Let’s see both types with the help of example:

Output:

[null, null, null]

How to declare and initialize String array in java

There are multiple ways to declare and initialize array in java.

Using new operator

We can declare and initialize array in java using new operator. We don’t have to provide size in this case.

You can also use variable name before [].

Without Using new operator

We can also declare and initialize array in java without using new operator.

Splitting declaration and initialization of String array

We can also declare a String array and can initialize it later.

Using Arrays.fill() to initialize String array

We can also declare a String array and can initialize it later.

Output:

[One, One, One, Two, Two, One, One]

Using Java 8’s setAll() method to initialize String array

We can also use Java 8’s setAll() method and pass a generator to initialize String array in java.

Output:

[One, One, One, One, One, One, One]

How to declare and initialize an empty String array

There are two ways to create empty String array in java.

Output:

[] []

That’s all about how to declare a String array in java.

Was this post helpful?

Leave a Reply

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