Hi,if I have array of objects {first(name,age),second(name,age)}
How can I access first (name) in java
Thanks

In the same way you access any element in any array:

// initializing the ARRAY:
MyCustomClass [] array = new MyCustomClass[2];
// array is not null, but array[0], array[1] are null


// array[0] is a MyCustomClass
array[0] = new MyCustomClass(....);
array[1] = new MyCustomClass(....);
// array[i] are now created

....

System.out.println(array[0].getName());

....

// we call the .length method and take each element
for (int i=0;i<array.length;i++) {
  MyCustomClass mc = array[i];
 
  System.out.println(mc.getName()+", "+mc.getAge());
}

Thanks for the respond
This is my code ,when I am printing throw all objects everithing works fine ,but when I try to loop throw the name It gives me exeption

package array;
import java.util.*;
public class test {

	public static void main(String[] args) {
		String name="";
		int age = 0;
		String ocupation="";
		int choice=1;
		int counter=0;
		People array[]=new People[10];
		while(choice==1){
		Scanner input=new Scanner(System.in);
		System.out.print("Enter your name: ");
		name=input.nextLine();
		System.out.print("Enter your age: ");
		age=input.nextInt();
		System.out.print("Enter your ocupation: ");
		ocupation=input.next();
		System.out.println("Enter your choice: ");
		choice=input.nextInt();
		counter++;
		People peopleObj =new People(name,age,ocupation);
		array[counter]=peopleObj;
		
		}
		for(int i=0;i<array.length;i++){
			System.out.println(array[i].getName());
		}


	}
	
}

Arrays begin with index 0. But you have the counter to be 0, then you increase it and then you add:

int counter = 0;

while () {

counter++ // you wrongfully increase the value and then you add:
array[counter]=peopleObj;
}

First you must add to the array and you must increase the counter. the first time the counter would be 0 and you would do this:

array[counter]=peopleObj; (array[0]=peopleObj)

Then you must increase the counter not before.


Also if you exit the while, not all of the elements of the array would have value. Some would be null. That is why you get the error.
Try this:

for(int i=0;i<array.length;i++) {
  System.out.println(array[i]);
}
// some of the above would be null.

// the right way is:
for(int i=0;i<counter;i++) {
  System.out.println(array[i]);
}

So you can print only the elements of the array that have been initialized

This article has been dead for over six months. Start a new discussion instead.