Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to create an Object array and how to work with it

Status
Not open for further replies.

zavrisky

Programmer
Oct 6, 2001
7
AU
class test
{
void printLine()
{
System.out.println("Hello World");
}
}

class drive
{
public static void main(String args[])
{
test obTest[] = new test[10];

obTest[0].printLine();
}
}


My objective is to create an array of a class object and to work with it. The above one is a test code, and probably I am missing something as it is not working. Help me out someone.
I am a beginner, sorry for the dumb question.
and thanks in advance
Zavrisky
 
With this line
test obTest[] = new test[10];
you have meade the declaration but the array is still empty you have to fill it with test-Objects
ex.
for(int i=0; i<obTest.length; i++)
obTest=new test();
 
//See below - arrays are initialized to nulls by JVM

class test
{
void printLine()
{
System.out.println(&quot;Hello World&quot;);
}
}

class drive
{
public static void main(String args[])
{
test obTest[] = new test[10];
/*Next line added by me to create a non-null object reference, since the object array above is simply being created, but, since no constructor is being called, is initialized by the JVM to all &quot;nulls&quot;.*/
obTest[0] = new test();//First array element initialized
// by assigning to it the reference returned by
// the constructor call, 'new test()' .
obTest[0].printLine(); //This now works
//Also, let's setup a test object in the array's 10th pos.
obTest[9] = new test();
obTest[9].printLine(); // This prints another line.
// The other 8 array items are still null object refs,
// and cannot be used. The two in use refer to
// anonymous objects. The array has a name, but the
// objects represented by it do not have names.
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top