How to update a single array using multiple instances of a class

How can I make two instances of a class, update the same array from that class? Like here, I want r1 and r2 to update same pendingOrders, so that finally the array is [‘yo’, ‘lo’]. That is not happening, the r1 and r2 are making different arrays.

import java.util.ArrayList;

public class Student{

    static int enrollmentNumber;
    String studentName;

    Student(String name){
        enrollmentNumber += 1;
        studentName = name;

    public String toString(){
        return enrollmentNumber+": "+this.studentName;

    public static void main(String[] args) {

        Student s = new Student("Pam");
        Student s1 = new Student("Hellooo");

        Student s2 = new Student("Pam2");
        Robot r1 = new Robot("Bob");
        System.out.println(r1.returnList()); // prints: ['yo']
        Robot r2 = new Robot("Rob");
        System.out.println(r2.returnList()); // prints: ['lo']
        // But I want it to print ['yo', 'lo']


class Robot{
    public ArrayList<String> pendingOrders = new ArrayList<String>();
    String rName;

    Robot(String name){
      rName = name;

    public void addToQueue(String s){
    public ArrayList returnList(){
        return pendingOrders;

>Solution :

Add the static keyword to the pendingOrders in Robot.
Check this guide for more info

Leave a Reply