Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, May 8, 2017

How to create array of objects of a class java


class sortcls
{
public int id;
public char val;
public sortcls(int x,char b)
{
id=x;
val=b;
}
public void print()
{
System.out.println("id= "+this.id+" val "+this.val);
}
}


//main
sortcls [] arr=new sortcls[n];
for(int i=0;i<n;i++)
{
int temp1=ab.nextInt();;
char temp2=ab.next().charAt(0);;
arr[i]=new sortcls(temp1,temp2);
}
for(int i=0;i<n;i++)
arr[i].print();


Explanation :
 sortcls [] arr=new sortcls[n]; will create reference to arr but not n objects ,if you try to access you will get null point exception

arr[i]=new sortcls(temp1,temp2); will create a new object 

0 Comments:

Post a Comment

Stats