• Post Reply Bookmark Topic Watch Topic
  • New Topic

Query Regarding Null Pointer Exception While trying to initialize an element of an array  RSS feed

 
Azeem Mohammed
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am getting a java.lang.NullPointerException if i do the following:

//Code snippet starts
double [] [] myMatrix=new myMatrix[3][];
myMatrix[0][0]=1.2D;//this is the line which raises the java.lang.NullPointerException
//Code snippet ends

Can anyone tell me what's wrong with the above code?

Thanks.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Azeem Mohammed wrote:double [] [] myMatrix=new myMatrix[3][];

That is not going to work. It needs to be double[][] myMatrix = new double[3][];

Azeem Mohammed wrote:
myMatrix[0][0]=1.2D;//this is the line which raises the java.lang.NullPointerException

That is because you didn't initialize the array: myMaxtrix[0] = new double[3];
 
Mohamed Sanaulla
Bartender
Posts: 3185
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to initialize the individual arrays of myMatrix.

Update: Had typed this, but was really late to post the reply . Wouter has a more detailed reply
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
new double[3][] creates an array of double[]. All these elements are still null. You need to initialize them like Wouter suggested. If you provide both dimensions when creating, new double[3][3], then all the elements of the outer array are also initialized.
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohamed Sanaulla wrote: . . . Update: Had typed this, but was really late to post the reply . . .
You have come across the term "race condition" in multi-threading? Well, these discussions are called threads, and you and Wouter were multi-threading in a race condition This time, Wouter won. Next time, good luck to you
 
zameel amjed
Greenhorn
Posts: 14
Notepad PHP Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Array declaration is not correct. mention the data type in right side with no of elements

 
Azeem Mohammed
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot everyone.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!