Home > Net >  Why is it necessary to import Scanner in both main and separate class?
Why is it necessary to import Scanner in both main and separate class?

Time:03-01

I created a basic calculator program using two classes, Main and Calculator. One of my methods in the Calculator class takes in a Scanner object as its parameter. I tried to delete the Scanner import from this class but IntelliJ puts it back automatically every time. Why does this class need the Scanner import if Scanner is already imported in main?

CodePudding user response:

You don't need to import anything. To use a class, it is sufficient that it can be found via your classpath, or implicitly for classes in the 'java' namespace. I view it as importing names, not importing classes (this is possibly not the way the language spec describes it).

'import' just allows you to refer to classes (etc.) by simple names, avoiding the need to type fully-qualified class names.

Here is using Scanner without import. This is the entire program.

class n {
  public static void main(String... a) {
    java.util.Scanner s = new java.util.Scanner(System.in);
    int n = s.nextInt();
    System.out.printf(" => %d\n", n);
  }
}

So, you 'import' when you need to use the class in a particular file, and don't feel like doing all the typing.

I don't use IntelliJ so cannot comment why it might fight you.

CodePudding user response:

In Java, imports are per file, so it is expected. If you need to use a Y class in n different files (in a different package) you will need to import it in each file. Some other useful details.

  1. You can use package.* to import all classes in a package.
  2. Is not necessary to import classes when used from the same package.
  3. You can use import static java.lang.Math.*; to import static members of a class.
  • Related