Videos
package project72;
import java.util.*;
import java.util.Scanner;
public class test1{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
}
}is Scanner a Class?? (I'm assuming of course it is)
is Scanner a Class in this particular code below? if not what is it ? and what role is Scanner playing inside this code also what is System.in here??
why is it inside parenthesis and what is it doing ??
System.in is simply an InputStream. A pretty generic interface designed many years ago. Changing this aspect would break a lot of existing code. So changing the type of System.in is a no go.
Adding the scanner methods to the stream would bloat the existing class on the other hand. Think of concepts such as single responsibility principle or segregation of concerns.
You see - good object oriented design is about having small classes that have one responsibility. Not two, not 5 or 10.
But I think you have a certain point - and if Java would be rewritten today, that input stream might end up being more convenient.
Scanner is a class which is defined in the standard Java Class Library, that you can use it to read from the console like this:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
however there are even more options that this constructer can do, for example you can read from a file and not console like this:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
so basically depending on the constructer you can choose where you want to read your input from.
Additionally, there are multiple ways to represent integers in a stream. Scanner.nextInt() reads them as a text string. DataInputStream.readInt() reads them as binary data.
If you mix them up, a human would enter 1234 and get 825373492, or a computer would enter 825373492 and get 1234. Both would be confused. By having to specify Scanner or DataInputStream, there are no such surprises or bugs, because you state up front what "read an integer" means.
Read this: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html