John R
John R

Reputation: 3026

Java initialize variable or array?

This line of code gives the following warning:

    short[] sh = null;

    for (int i = 0, n = b.length; i < n; i++) {
        sh[i] = 0;

    }  

warning: The variable sh can only be null at this location.

short[] sh;

for (int i = 0, n = b.length; i < n; i++) {
    sh[i] = 0;

} 

And, this code gives the following warning:

warning: The local variable sh may not have been initialized.

Upvotes: 0

Views: 575

Answers (5)

Phil
Phil

Reputation: 3520

You just declared a variable.

You need to create the array:

short[] arr = new short[size];

Upvotes: 1

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

sh is a variable that represents an array of shorts.

warning: The variable sh can only be null at this location.

sh is initialized but not properly, it is null:

short[] sh = new short[b.length];

warning: The local variable sh may not have been initialized.

Since the local variables are not initialized automatically like instance variables you have to initialize it.

Upvotes: 0

Desmond Zhou
Desmond Zhou

Reputation: 1399

Initialization means to create the array, in Java use the "new" keyword

short[] arr = new short[10];

Upvotes: 0

Joe
Joe

Reputation: 82584

sh will always be null in your code:

short[] sh = new short[b.length];

Upvotes: 0

Mysticial
Mysticial

Reputation: 471199

This is because you need to initialize the array. Try this:

short[] sh = new short[b.length];

If you don't initialize, you will get those warnings, and will get NullPointerException if you run it.

Upvotes: 2

Related Questions