I know that object is created by first declaration and then initialization.
But all of these objects are created inside of a method.
When I try to create an object inside a class but outside of a method then it gives error.
So, why aren't we allowed to create objects outside of a method? Also, does creating object inside of a methods has any advantages?
Amol Araragi wrote:I know that object is created by first declaration and then initialization. . . .
No, that is how you create a non‑null reference. There are several ways to create objects, but the new operator is a frequently used technique. String literals are objects in their own right, so a String literal and String concatenation are also ways to create objects.
What you may get wrong is an assignment statement:-Line 2 is an assignment statement and you are only allowed statements inside methods, constructors or initialisers. That is probably why you can't get your code to compile.
It is useful to declare and initialise a field in one line if you always want to have the same value for that field for all instances of the class. It is better to initialise static fields like that than to try initialising them in the constructor. I shall leave it to you to find out why.