Joshua
Joshua

Reputation: 305

What does "Variable might not have been initialized" mean?

public static double[] processUserInput(String data) {
        String[] arrayInString;
        double[] arrayInDouble;
        int length;

        if( data.contains(",") ) {
            arrayInString = data.split(",");

            length = arrayInString.length;

            for(int i = 0; i < length; i++) {
                arrayInDouble[i] = Double.parseDouble( arrayInString[i] );
            }
        }

        return arrayInDouble;

    }

I am using Netbeans and the compiler is saying that variable arrayInDouble might not have been initialized. What does that mean?

Upvotes: 0

Views: 5191

Answers (4)

Jim Garrison
Jim Garrison

Reputation: 86774

    String[] arrayInString;

This is not initialized but you provide a value (arrayInString = data.split(",");) before referring to it so there is no complaint.

    double[] arrayInDouble;

This is also uninitialized. If the input does not contain a comma, you skip all the code and then attempt to return the value of arrayInDouble. The warning says that when you execute the return, arrayInDouble may not have a value.

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34166

In this

String[] arrayInString;
double[] arrayInDouble;

you are just declaring them, before you use them, you also need to initialize:

String[] arrayInString = new String[length1];
double[] arrayInDouble = new double[length2];

where length is the length of the array.

PS: There are other ways to initialize them, for example:

double[] arrayInDouble = {1.1, 2.2}; // The length of the array will be the number of elements in brackets

Upvotes: 1

Prasad Kharkar
Prasad Kharkar

Reputation: 13566

You have not assigned any values to these variables

 String[] arrayInString;
 double[] arrayInDouble;

These variables are local variables so they need to be initialized before using as they will not get any default value for them.

Upvotes: 0

Ajinkya
Ajinkya

Reputation: 22720

You need to initialize them (assign some value) before using them.

Upvotes: 0

Related Questions