Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

What's wrong with this Java code please?

Let:

public class record {

String name;

public void show(){

System.out.println("Name: "+name);

}

}

This one works very well:

public class test {

static record rec;

public static void main(String[] args) {

rec = new record;

rec.name="Toky";

rec.show();

}

}

So what's wrong with this one ? (no error during the edition, but can't run with the message : Exception in thread "main" java.lang.NullPointerException

at BPlusTree.test.main(test.java:8))

public class test {

static record[] rec;

public static void main(String[] args) {

rec = new record[2];

rec[1].name="Toky";

rec[1].show();

}

}

THANKS A LOT.

1 Answer

Relevance
  • 1 decade ago
    Favorite Answer

    Just glancing at it I would say that rec[1] should be rec[0], but that does not work either. The error refers to the array being null. When rec[0] or rec[1] is null it cannot have a name assigned to its name variable. This worked for me:

    static record recTmp;

    static record[] rec;

    public static void main(String[] args)

    {

    recTmp = new record();

    rec = new record[2];

    recTmp.name = "Toky";

    rec[0]=recTmp;

    rec[0].show();

    }

Still have questions? Get your answers by asking now.