• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Array of objects

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are no compilation errors, but when i run the program I get an NullPointerException in the indicated line below. How do I rectify this?

class A
{
int i,j;
}
public class ArrayObjects
{
public static void main( String args[] )
{
A ob[]= new A[5];
for( int i=0; i<5; i++ )
{
ob[i].i=1; //NullPointerException
ob[i].j=2;
}
}
}
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think that the following line,

A ob[]= new A[5];

just created 5 reference to type of A.
You have not created the Object and assign to the reference yet.

Ziji
 
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Doesn't look like SCJD problem.
 
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ajay Divakaran:
There are no compilation errors, but when i run the program I get an NullPointerException in the indicated line below. How do I rectify this?

class A
{
int i,j;
}
public class ArrayObjects
{
public static void main( String args[] )
{
A ob[]= new A[5];
for( int i=0; i<5; i++ )
{
ob[i].i=1; //NullPointerException
ob[i].j=2;
}
}
}



Not an SJCD problem but I'll answer befroe it is moved. A ob[]= new A[5]; creates and array of size 5. But the objects within the array have not been intialised so the references default to null. This is the same as the statement A ob[]= {null,null,null,null,null};
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic