Java import statement not at the beginning of the file
Question: In python, the import statement can be placed everywhere in the file, even
inside a _class_ , or an _if_.

Is there a way to accomplish the same thing in _Java_? I understand that it
could be a bad practice not to put all the imports at the top of the file, I'm
just wondering if it is possible in some way or not.


Answer: The very first statement in a Java file must be (if there is one) the package
statement, followed by the import statements.

They can not be placed in another location.

However, it is possible to use an alternative way (which I personally don't
recommend)

    
    
    import myPackage.MyClass;
    
    public class Test{
      private MyClass instance = new MyClass();
    }
    

can be rewritten as:

    
    
    public class Test{
      private myPackage.MyClass instance = new myPackage.MyClass();
    }
    

There is no import statement needed anymore (which comes in handy if you need
to use two classes with the same name within one Java file), but you put the
entire path to the class, including package in the declaration/initialization
of the variables.

In this way, they can be about anywhere in the code.

