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

Recommended Answers

All 3 Replies

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




// 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];
		Scanner input=new Scanner(System.in);
		System.out.print("Enter your name: ");
		System.out.print("Enter your age: ");
		System.out.print("Enter your ocupation: ");
		System.out.println("Enter your choice: ");
		People peopleObj =new People(name,age,ocupation);
		for(int i=0;i<array.length;i++){


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:

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++) {
// some of the above would be null.

// the right way is:
for(int i=0;i<counter;i++) {

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.