In the two examples, you are trying to achieve two completely different things.
In the first example, you declare an ArrayList inside the main method, so the list area will be exactly that method. The closing class is completely unrelated to this ArrayList .
In the second, you try to create a data item named exams in the InvokeMethod class. This means that each instance of this class will have its own list.
Adding elements does not work, because "from methods" can only be declaration and initialization. To fix this, you can use the initialization block :
public class InvokeMethod { ArrayList<String> exams = new ArrayList<String>(); { exams.add("Java"); exams.add("C#"); } public static void main(String[] args) { } }
or, class constructor:
public class InvokeMethod { ArrayList<String> exams = new ArrayList<String>(); public InvokeMethod() { exams.add("Java"); exams.add("C#"); } public static void main(String[] args) { } }
Note. . You can also extract this list from the main method through an instance of the InvokeMethod class:
public class InvokeMethod { ArrayList<String> exams = new ArrayList<String>(); public InvokeMethod() { exams.add("Java"); exams.add("C#"); } public static void main(String[] args) { InvokeMethod invokeMethod = new InvokeMethod(); System.out.println(invokeMethod.exams.toString()); invokeMethod.exams.add("Delphi"); System.out.println(invokeMethod.exams.toString()); } }
will print
[Java, C#] [Java, C#, Delphi]
source share