Input/Output in Java
- Categories Introduction to Java, Math Library, Java
Q.1 What is a stream?
Ans.
- A stream is an abstraction that brings in or sends data.
- Stream is actually a sequence of data.
- Streams are one way either input or output.
- Streams are typically connected to a data source, or data destination, like a file, network connection etc.
Q.2 Which stream is opened automatically by java?
Ans. There are three streams connected with console that are opened automatically for us:
- System.out: standard output stream (Console by default)
- System.in: standard input stream (Keyboard by default)
- System.err: standard error stream (Console by default)
Q. 3 What is java scanner class?
Ans. Java Scanner class comes under the java.util package. The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default. It provides many methods to read and parse various primitive values. Java Scanner class is widely used to parse text for string and primitive
Q. 4 What are the different methods to read from Java scanner class?
Ans.
Method | Description |
---|---|
nextBoolean() | Reads a boolean value from the user |
nextByte() | Reads a byte value from the user |
nextDouble() | Reads a double value from the user |
nextFloat() | Reads a float value from the user |
nextInt() | Reads a int value from the user |
nextLine() | Reads a String value from the user |
Next() | Reads a String value from the user (till first space) |
nextLong() | Reads a long value from the user |
nextShort() | Reads a short value from the user |
Q. 5 How do you read a character as input from user?
Ans. We read in a character by reading a string and then using charAt() method to extract first character from it.
So the command is: next().charAt(0);
Q. 6 What is difference between next and nextLine?
Ans.
next() | nextLine() |
---|---|
Finds and returns the next complete token from this scanner. | nextLine() reads input including space between the words i.e. it reads till the end of line |
Can read the input only till the space. | Can read spaces |
It places the cursor in the same line after reading the input. | Once the input is read, nextLine() positions the cursor in the next line. |
Q. 7 What is bufferedreader class in Java?
Ans. BufferedReader is Java class to reads the text from an Input stream (like a file) by buffering characters that seamlessly reads characters, arrays or lines. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It improves the performance by buffering the input.