0

I am trying to make a method that build new object of the class (PhoneBook) using different constructors according to the number of parameters ,, but it gives an error

( Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 )

public static PhoneBook createObjects(String fName,String lName,String num,String...optional)
{
    n++;    
    if (optional[0]==null)
        ArrayOfObjects[n]=new PhoneBook(fName,lName,num);
    else if (optional[1]==null)
        ArrayOfObjects[n]=new PhoneBook(fName,lName,num,optional[0]);

    return ArrayOfObjects[n];   
}
2
  • @Vipar maybe a PhoneBook array declared somewhere else in OP's code (not relevant to the question)? Commented Dec 9, 2012 at 19:04
  • @Vipar actually I start n with 0 , but why this array never take values ? Commented Dec 9, 2012 at 19:14

2 Answers 2

3

Instead of checking whether optional[0] == null, you should examine optional.length to determine if the optional parameter is present.

The same goes for optional[1].

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

Comments

0

Rather than checking optional[0] and optional[1] here, you should check to optional.length. Also, keep in mind that optional itself may well be null, so something like:

if(optional != null) {
    if(optional.length > 0) {
        // I now know that optional has at least one element in it, and optional[0] should be valid, though I don't know that it is non-null.
        if(optional.length > 1) {
            // I now know that optional[1] is valid, though I do not know it is non-null.
        }
    }
}

if you NEED non-null:

if(optional.length > 0 && optional[0] != null)

The second part, optional[0] != null will only be called if the first evaluates to true.

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.