Is it always required to
import java.util.Scanner;
at the beginning of your code in each of your java programs?
Is it always required to
import java.util.Scanner;
at the beginning of your code in each of your java programs?
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
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.
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");
}
}
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;