-3

Is it always required to

import java.util.Scanner;

at the beginning of your code in each of your java programs?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

4 Answers4

0

When you want to create a program that uses some class such as java.util.Scanner you need to write import java.util.Scanner; (or the type of class you need)

for example, you can run this program:

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

but you can't run this program without import java.util.Scanner;

public class MyClass {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int num = read.nextInt();
        System.out.println("You wrote " + num);
    }
}

sorry if my english is not so good

Ofek
  • 1,065
  • 6
  • 19
  • But like is that module always required to have? – dillythecoder Sep 19 '21 at 03:11
  • you need this module if you are using Scanner in your code – Ofek Sep 19 '21 at 03:12
  • you probably will learn about other kind of classes, like FileInputStream that write data to file. and to use these classes you would need to write the matching import. – Ofek Sep 19 '21 at 03:15
  • @dillythecoder there is some explanation here: https://www.tutorialspoint.com/why-do-we-use-import-statement-in-java-where-it-should-be-included-in-the-class – Ofek Sep 19 '21 at 03:19
0

The import java.util.Scanner; is a Text Scanner and isn't required if your code does not have the need to read some file/data by the user/etc.

0

If you want to get from the user input you should use class Scanner otherwise, you don't need it.

Try this code without input user:

public class Test {
    public static void main(String[] args) {
        System.out.print("hello world");
    }
}
F. Müller
  • 3,969
  • 8
  • 38
  • 49
0

It depends on your needs. Think what it means ( import java.util.Scanner ) It means you want to use a scanner class which is available in java.util package. So you import it when you need not every time. Real Life example: You need a Math book from your book shelve which is in your room. Here shelve is your package and shelve is in your room.

To get Math book you need to go your room then shelve then Math book

Hence room.shelf.Math;

Ajay J
  • 49
  • 8