Mirco Chen
Mirco Chen

Reputation: 11

return a single object in an object array

I'm new to programming and I was wondering how do you return a single object from an object array This is the part of the code I'm having trouble in:

public Class methodName(){
    x = 3;
    if(array[x] != null){
        Class y = array[x];
    }
    return y;
}

it gives me an error on the "y"

y cannot be resolved to a variable

Upvotes: 0

Views: 190

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45735

Because y is declared inside of the if, it's unavailable outside of the if.

Declare it outside of the if with a default value, then reassign it inside the if:

public Class methodName(){
    x = 3;
    Class y = null; // Defaults to null if not reassigned later
    if(array[x] != null){
        y = array[x]; // Reassign the pre-declared y here if necessary
    }
    return y;
}

This will return the default null if array[x] == null.

Look up how variables are scoped to learn what's going on here. Basically, if a variable is declared within a {}, it can't be used outside of the {} (although that's a gross over-simplification).

Upvotes: 1

Related Questions