• 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:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

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};
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic