Q:

Calling a method on an Object from within a Class vs from within a method

This might be a really elementary question but it puzzles me at this stage of my Java learning.
I have got the following piece of code:
    package com.soti84;

    import java.util.ArrayList;

    public class InvokeMethod {

    public static void main(String[] args) {

    ArrayList<String> exams= new ArrayList<String>();
    exams.add("Java"); 
    exams.add("C#");    

    }           

    }

If I move the line that instantiates the ArrayList object and the calls on that object outside the method, the line that creates the object is fine but the add() method calls on the object are not allowed. Why is that?
    package com.soti84;

    import java.util.ArrayList;

    public class InvokeMethod {
    ArrayList<String> exams= new ArrayList<String>();
    exams.add("Java"); 
    exams.add("C#");    

    public static void main(String[] args) {

    }   

    }

Thanks.

A:

You simply can't do that code outside of methods. If you wanted to do this you would need initializer block or static block.
public class InvokeMethod {
    ArrayList<String> exams= new ArrayList<String>();
    {
      exams.add("Java"); 
      exams.add("C#"); 
    }

Now that block is gonna execute when you create an instance. If your variable was static, you could make that block static (just add static before that block). Static block is gonna execute when your class is initialized. Those blocks can be quite convenient when you need a populated static list/map. Ofcourse, everything that is convenient in programming is probably a bad practice, and same here, those blocks are frowned upon by some people, they can be quite dangerous and lead to hard-to-find bugs (mostly about the order of execution).

