I can’t initialize an array of objects with scanner in java [duplicate]

This question already has an answer here:

I’m new to OOP and I’m trying to write a simple code which builds a Contact Manager. In the main class I build an array of Contact objects and I try to initialize them by getting information from the user through scanner object. But I get this error at the runtime:

Exception in thread "main" java.lang.NullPointerException

and the exception belongs to this line in the main class:


these are my classes:

 import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        ContactManager contactManager = new ContactManager();
        Contact[] contacts = new Contact[5];
        Scanner scanner = new Scanner(System.in);
 for (int cnt = 0 ; cnt < 5 ; cnt++){
        System.out.println("New Contact:");

    String searchName = scanner.nextLine();
    Contact foundContact = contactManager.searchContact(searchName);

Contact class:

public class Contact {

private String name;
private String email;
private String phoneNumber;

public void setName(String name){
    this.name = name;

public void setEmail(String email){
    this.email = email;

public void setPhoneNum(String phoneNumber){
    this.phoneNumber = phoneNumber;

public String getName(){
    return this.name;

public String getEmail(){
    return this.email;

public String getPhoneNum(){
    return this.phoneNumber;

and ContactManager class:

public class ContactManager {
private Contact[] myFriends;
private int friendsCount;

    friendsCount = 0;
    myFriends = new Contact[500];

void addContact(Contact contact){
    myFriends[friendsCount] = contact;

Contact searchContact(String searchName){
    for (int cnt = 0 ; cnt < friendsCount ; cnt++ ){
        if (myFriends[cnt].getName().equals(searchName)) {
            return myFriends[cnt];
    return null;