Write a Java program to ArrayList of user defined objects


The User class is defined with two private instance variables name and age and a constructor which takes in the name and age parameters and sets them. It also contains getter and setter methods to access and modify the private instance variables respectively.

In the UserDefine_Object class, an ArrayList named users is created to hold User objects. Four User objects are created using the User class constructor and added to the users list using the add() method.

The forEach() method is then used to loop through the users list and print out the name and age of each User object using lambda expressions. The getName() and getAge() methods of the User class are used to retrieve the name and age values of each User object.

Overall, this code demonstrates how to create a custom class, instantiate objects of that class, and store those objects in an ArrayList.

Source Code

import java.util.ArrayList;
import java.util.List;
public class UserDefine_Object
{
	public static void main(String[] args)
	{
        List<User> users = new ArrayList<>();
        users.add(new User("Tara", 22));
        users.add(new User("Siva", 31));
        users.add(new User("Pooja", 25));
        users.add(new User("Ram Kumar", 27));
 
        users.forEach(user -> {
            System.out.println("Name : " + user.getName() + "\nAge : " + user.getAge());
        });
    }
}
class User {
    private String name;
    private int age;
 
    public User(String n, int a)
	{
        name = n;
        age = a;
    }
 
    public String getName()
	{
        return name;
    }
 
    public void setName(String n)
	{
        name = n;
    }
 
    public int getAge()
	{
        return age;
    }
 
    public void setAge(int age)
	{
        this.age = age;
    }
}
 

Output

Name : Tara
Age : 22
Name : Siva
Age : 31
Name : Pooja
Age : 25
Name : Ram Kumar
Age : 27

Example Programs