0

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
1
  • 3
    java is block scoped not function scoped. you can fix by declaring y before the if block with a default value. Commented Jan 13, 2018 at 16:55

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.