public class first {
ArrayList<String> al= new ArrayList<String>();
al.add("Batman"); //it doesn't work
public static void main(String[] args) {
}
}
Why doesn't it allow to use add method outside of main?
public class first {
ArrayList<String> al= new ArrayList<String>();
al.add("Batman"); //it doesn't work
public static void main(String[] args) {
}
}
Why doesn't it allow to use add method outside of main?
You're missing brackets.
Try this code:
public class first {
ArrayList<String> al= new ArrayList<String>();
{
al.add("Batman");
}
public static void main(String[] args) {
}
}
I don't know why the creators of the Java language came to the conclusions they did, so unfortunately the best answer I can give is: It cannot be done because the Java language (compiler) does not allow you to do it.
What you can do is surround that method call in curly braces and then it becomes an initializer block.
This is a similar question: Why is this Java code in curly braces ({}) outside of a method?
A class
has the following structure: attributes
(your arraylist
) followed by functions
( like main()
).
To do any manipulations on an attribute
, it must be done within a function
. This is done this way because it was designed this way.
"al" is an instance variable of class "first" and without declaring an object of class "first" you cannot add anything inside even main function.
If you have to add anything outside main function without creating an object of class then that instance must be static and then you can add string by putting it inside curly braces.
ArrayList<String> al = new ArrayList<>();
{
al.add("names");
}
It is a basic concept of Java or an architecture of Java, you can only declare variables and methods in class. All functionality related work should be done in functions only.
You can refer this link for Class definition, http://www.tutorialspoint.com/java/java_object_classes.htm
Patterns like factory method or fluent builder can be very helpful in java if no constructor exists because they allow you to declare, instantiate and initialize your objects in one same expression.
Here are examples for your case :
List<String> l = java.util.Arrays.asList("Batman");
ArrayList<String> al = new ArrayList<String>(java.util.Arrays.asList("Batman"));
ArrayList<String> al = com.google.common.collect.Lists.newArrayList("Batman");
The last example uses the Guava library. It has factory methods and/or builders for all kind of java collections.
As per Java Architecture you can't write any logical statement outside the method .