Search code examples
javamethodscallprogram-entry-pointcalling-convention

How do I call a method in java from main?


import java.util.*;

import java.io.*;

public class Test extends ArrayList
{

    ArrayList<String> list = new ArrayList<String>();

    public static void main(String[] args)
    {
        new Test().add();
        new Test().contains();
    }



    public boolean add(){
        list.add("cat");
        System.out.println(list);
        return true;
    }

    public void contains(){
        if (list.contains("cat")){
            System.out.println("list contains cat");
        }
        else{
            System.out.println("list doesn't contain cat");
        }

    }

}

Why isn't the result [cat] list contains cat? It keeps giving me [cat] list doesn't contain cat. The first method is working correctly, but why isn't the second one? Thanks... I'm really new to this.


Solution

  • That's because you're calling both the methods with different instances.

    new Test().add(); // Creates 1 instance
    new Test().contains(); // creates another instance
    

    You need to use the same instance to call both the methods.

    Test t = new Test();
    t.add();
    t.contains();
    

    Every new Test object created with by the new Test() has its own copy of list. That's why when you call contains() with the other instance, its still empty as the list of the first instance was only added with the string "cat".