getting "NullPointer Exception" while creating objects in a loop - java

I am trying to creating objects in a loop.
while executing this i am getting NullPointer Exception like below::
Exception in thread "main" java.lang.NullPointerException
at Test1.main(Test1.java:14)
Test1.java
public class Test1 {
public static void myMethod(int i)
{
System.out.println("calling #"+ i+"time");
}
public static void main(String arg [])
{
for(int i = 0;i<=999;i++)
{
Test1 obj[] = null;
obj[i] = new Test1();
obj[i].myMethod(i);
}
}
}
Is this the correct way of creating objects in a loop?

You haven't created any array yet. Just initialize the array before the loop -
Test1 obj[] = new Test1[1000];
for(int i = 0;i<=999;i++)
{
//Test1 obj[] = null; // <----------- don't want this here

The array hasn't yet been created.
Test1 obj[] = new Test1[1000];
You're getting the error because the the array is pointing to null, and hasn't been initialized.

Related

NoSuchField error in Java code with two classes

I have the following code:
public class Table {
Table2[] data = new Table2[2000];
public Table() {
for (int i = 0; i < data.length; i++) {
data[i] = new Table2();
}
}
}
And:
public class Table2 {
Integer[] data;
public Table2() {
data = new Integer[100];
}
Im having problems accessing Table.data[0].data[0]
Table.data[0].data[0] is not null.
The program works in Eclipse but outside of Eclipse i get a NoSuchField error. Im not sure how to fix this.
You must be doing some typo/mistake in your code accessing it. If you do it as follows, no matter where (eclipse or outside) you are accessing it, the result will be same.
public class Main {
public static void main(String[] args){
Table table=new Table();
table.data[0].data[0]=10;
System.out.println(table.data[0].data[0]);
}
}
Output:
10

Static class fields in construction

// package and import things..
public class A {
public int x;
public static A ob;
A() {
A.ob.x = 5;
}
public static void main(String args[) {
A.ob = new A();
System.out.println(ob.x);
}
}
Why this code is give NullPointerException ? If i change "A.ob.x" to "this.x", it's done. But already A.ob = this in this code?
A.ob = new A();
This first creates an A by executing the constructor, and then, assigns the created A to A.ob. It's basically equivalent to
A tmp = new A();
A.ob = tmp;
So, at the time the constructor is called, A.ob is still null. So you get a NullPointerException.

Eclipse error: java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Here is the exact error message:
Exception in thread "main" java.lang.NullPointerException
at Application.main(Application.java:22)
I've tried to fix it with what I know... what am I doing wrong?
My code:
public class Application {
private String guitarMaker;
public void setMaker(String maker) {
guitarMaker = maker;
}
public String getMaker() {
return guitarMaker;
}
public static void main (String[] args) {
Application[] guitarists;
guitarists = new Application[1];
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());
}
}
new Application[1] creates an array of one element, and all elements in that array (in this case, "all the elements" is "that only element") are null by default. That means that guitarist[0] is null, and calling setMaker on it will result in the NullPointerException.
You need to instantiate a guitarist and set assign it to guitarist[0]:
guitarist[0] = new Application();
public class Application {
private String guitarMaker;
public void setMaker(String maker) {
guitarMaker = maker;
}
public String getMaker() {
return guitarMaker;
}
public static void main (String[] args) {
Application[] guitarists;
guitarists = new Application[1];
guitarists[0] = new Application(); //need to create a new object
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());
}
}
You were calling a method on a null object. The new Application[1] just creates an array after that you need to make new objects in each index of the array
you have to initialise array with size and call new Application() instead of new Application[1] something like:
Application[] guitarists = new Application[1];
guitarists[0] = new Application();
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());

How do I correctly instantiate a public class+data structure in a class so that other objects can use it?

In my code, I have a seperate Runner class that instantiates a World, which has a 4x4 array of Locations (a separate class) stored as a Location[][] array. When I print/try to use the Location array, its value is null, and it throws a NullPointerException.
public class Runner
{
public static void main(String[] args)
{
...
WumpusWorld test_loc = new WumpusWorld();
System.out.print(test_loc) //This prints an ID for the WumpusWorld object
System.out.print(test_loc.world) //Null value prints here
//I'd like to pass the test_loc.world values to an actor here
...
}
}
The applicable code for the WumpusWorld is as follows:
public class WumpusWorld
{
public Location[][] world;
public WumpusWorld()
{
new WumpusWorld((byte) 4); //this constructor is used
}
...
public WumpusWorld(byte size)
{
this.world = new Location[size][size];
for(byte i = 0; i<size; i++)
{
for(byte j = 0;j<size;j++)
{
world[i][j] = new Location(j,i,true,false,false);
}
//Location instances called in the form world[x][y]
//are error free in constructor
...
}
}
Your problem might be in the way you call public WumpusWorld(byte size) from the default constructor.
Try this:
public WumpusWorld()
{
this((byte) 4);
}
With new in the call, I had uninitialized values in the inner class

How do I pass an array of strings into another method?

My code is like this:
public class Test() {
String [] ArrayA = new String [5]
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0])
}
}
I've tried various methods (No pun intended) but none worked. Thanks for any help I can get!
public class Test {
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
public Test(){ // Your Constructor
method1(arrayA[0]); // Calling the Method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, you can just call new Test();
OR if you want the method to be called from your main class by creating an instance of Test you may write:
public class Test {
public Test(){ // Your Constructor
// method1(arrayA[0]); // Calling the Method // Commenting the method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, create an instance of test in your main class.
Test test = new Test();
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
test.method1(arrayA[0]); // Calling the method
And call your method.
EDIT:
Tip: There's a coding standard that says never start your method and variable in uppercase.
Also, declaring classes doesn't need ().
If we're talking about passing arrays around, why not be neat about it and use the varargs :) You can pass in a single String, multiple String's, or a String[].
// All 3 of the following work!
method1("myText");
method1("myText","more of my text?", "keep going!");
method1(ArrayA);
public void method1(String... myArray){
System.out.println("The first element is " + myArray[0]);
System.out.printl("The entire list of arguments is");
for (String s: myArray){
System.out.println(s);
}
}
try this
private void Test(){
String[] arrayTest = new String[4];
ArrayA(arrayTest[0]);
}
private void ArrayA(String a){
//do whatever with array here
}
Try this Snippet :-
public class Test {
void somemethod()
{
String [] ArrayA = new String [5] ;
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1 (String[] A) {
System.out.println("Here's where I need ArrayA[0]"+A[0]);
}
public static void main(String[] args) {
new Test().somemethod();
}
}
The Class name should never had Test()
I am not sure what you are trying to do. If it is java code(which it seems like) then it is syntactically wrong if you are not using anonymous classes.
If this is a constructor call then the code below:
public class Test1() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0]);
}
}
should be written as this:
public class Test{
public Test() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1(String[] ArrayA){
System.out.println("Here's where I need " + ArrayA[0]);
}
}

Categories