Im still learning and have noticed many inconsistencies when it comes to coding. I take it Java is pretty much like Photoshop in the way that a single task can be done many different ways and still have the job done.
One of my main questions is when it comes to Scanner and Random.
In one source they have Scanner in the scope of the whole class
public class test {
private static Scanner input = new Scanner(System.in);
}
In another source they have it like this
public class test {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
}
}
What is the difference with this? Is there a right way and a wrong way?
The two ways you've initialized the Scanner are similar, but not quite the same.
The first always works because you're initializing the static variable when it's being created.
The second only works when test is the startup class, because public static void main(String[] args) is always called in an application's startup class.
The problem arises if you try to use a method of the test class from another class, like this:
public class test {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
}
public static void myMethod() {
input.hasNext();
}
}
and in a separate file
public class AnotherTest {
public static void main(String[] args) {
test.myMethod();
}
}
As soon as you run java AnotherTest, it will bomb with a NullPointerException on the input.hasNext() because test's main is never run and thus input is never initialized.
Edit: Side note, class names in Java are almost always capitalized.
There is a difference here!
If you want to access your scanner without invoking any method, then place it in field or static block.
Your example
private static Scanner input = new Scanner(System.in);
is only equal to this
private static Scanner input;
static {
input = new Scanner(System.in);
}
Initialization time is different. Method main is special method in which this is not visible, because this method start your program ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With