Kart
Kart

Reputation: 11

Assinging and Object to Array in Java, It is returning null

I have created a program and assigning customer object to customers array, but when I try to get the object in array it returns null. I am new to Java, please help me out where I am going wrong.

public class Customer {

    private String firstname,lastname;

    public Customer(String f,String l){
        this.firstname = f;
        this.lastname = l;
    }

    public String getFirstName(){
        return firstname;
    }

    public String getLastName(){
        return lastname;
    }   
}

public class Bank {

    private Customer [] customers;
    private int numberofCustomers;

    public Bank(){
        customers = new Customer [5];
        numberofCustomers = 0;

    }

    public void addCustomer(String f,String l){
        int i = numberofCustomers++;
        customers[i] = new Customer(f,l);
    }

    public int getNumberofCustomer(){
        return numberofCustomers;
    }

    public Customer getCustomerMethod(int index){
        return customers[index];
    }
}

public class TestAccount {

public static void main (String [] args){

        Bank b = new Bank();
        b.addCustomer("Test", "LastName");
        System.out.print(b.getNumberofCustomer());
        System.out.print(b.getCustomerMethod(1));

    }
}

Upvotes: 1

Views: 116

Answers (3)

PermGenError
PermGenError

Reputation: 46398

Array indexes start with zero. You have added a customer at index 0 first element in your array and you should use the same index to get the element. currently there is nothing at index 1 thus your code returns null;

System.out.print(b.getCustomerMethod(0));

Say array size is 5, thus its indexs would be 0,1,2,3,4 where 0 is the first index and 4 is the last index.

After this line b.addCustomer("Test", "LastName"); your array will be :

Array: [Customer("Test", "LastName") , null , null, null, null]
Index:                0             ,  1   ,  2  ,   3 ,  4

and when you try ' System.out.print(b.getCustomerMethod(1));' It returns null. as you can see that your array has null at index 1.

Upvotes: 5

Narendra Pathai
Narendra Pathai

Reputation: 41935

There are three problems with your code:

  • Indexes start with 0
  • You are using post increment operator to assign value to i. int i = noOfCustomers++; will result in value of i as 0. So you are adding the customer at index 0 and fetching from index 1. So you get null
  • Bank should be using ArrayList

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200138

You added one customer and then you are asking for the second one. Arrays indices are zero-based.

Upvotes: 0

Related Questions