[java] What is the use of System.in.read()?

What is the use of System.in.read() in java?
Please explain this.

This question is related to java

The answer is


Two and a half years late is better than never, right?

int System.in.read() reads the next byte of data from the input stream. But I am sure you already knew that, because it is trivial to look up. So, what you are probably asking is:

  • Why is it declared to return an int when the documentation says that it reads a byte?

  • and why does it appear to return garbage? (I type '9', but it returns 57.)

It returns an int because besides all the possible values of a byte, it also needs to be able to return an extra value to indicate end-of-stream. So, it has to return a type which can express more values than a byte can.

Note: They could have made it a short, but they opted for int instead, possibly as a tip of the hat of historical significance to C, whose getc() function also returns an int, but more importantly because short is a bit cumbersome to work with, (the language offers no means of specifying a short literal, so you have to specify an int literal and cast it to short,) plus on certain architectures int has better performance than short.

It appears to return garbage because when you view a character as an integer, what you are looking at is the ASCII(*) value of that character. So, a '9' appears as a 57. But if you cast it to a character, you get '9', so all is well.

Think of it this way: if you typed the character '9' it is nonsensical to expect System.in.read() to return the number 9, because then what number would you expect it to return if you had typed an 'a'? Obviously, characters must be mapped to numbers. ASCII(*) is a system of mapping characters to numbers. And in this system, character '9' maps to number 57, not number 9.

(*) Not necessarily ASCII; it may be some other encoding, like UTF-16; but in the vast majority of encodings, and certainly in all popular encodings, the first 127 values are the same as ASCII. And this includes all english alphanumeric characters and popular symbols.


This example should help? Along with the comments, of course >:)

WARNING: MAN IS AN OVERUSED FREQUENT WORD IN THIS PARAGRAPH/POST

Overall I recommend using the Scanner class since you can input large sentences, I'm not entirely sure System.in.read has such aspects. If possible, please correct me.

public class InputApp {

// Don't worry, passing in args in the main method as one of the arguments isn't required MAN

    public static void main(String[] argumentalManWithAManDisorder){
        char inputManAger;

        System.out.println("Input Some Crap Man: ");
        try{
            // If you forget to cast char you will FAIL YOUR TASK MAN
            inputManAger = (char) System.in.read();
            System.out.print("You entererd " + inputManAger + " MAN");
        }
        catch(Exception e){
            System.out.println("ELEMENTARY SCHOOL MAN");
        }
    }
}

It allows you to read from the standard input (mainly, the console). This SO question may helps you.


import java.io.IOException;

class ExamTest{

    public static void main(String args[]) throws IOException{
        int sn=System.in.read();
        System.out.println(sn);
    }
}

If you want get char input you have to cast like this: char sn=(char) System.in.read()

The value byte is returned as int in the range 0 to 255. However, unlike in other languages’ methods, System.in.read() reads only a byte at a time.


System is a final class in java.lang package

code sample from the source code of api

public final class System {

   /**
     * The "standard" input stream. This stream is already
     * open and ready to supply input data. Typically this stream
     * corresponds to keyboard input or another input source specified by
     * the host environment or user.
     */
    public final static InputStream in = nullInputStream();

}

read() is an abstract method of abstract class InputStream

 /**
     * Reads the next byte of data from the input stream. The value byte is
     * returned as an <code>int</code> in the range <code>0</code> to
     * <code>255</code>. If no byte is available because the end of the stream
     * has been reached, the value <code>-1</code> is returned. This method
     * blocks until input data is available, the end of the stream is detected,
     * or an exception is thrown.
     *
     * <p> A subclass must provide an implementation of this method.
     *
     * @return     the next byte of data, or <code>-1</code> if the end of the
     *             stream is reached.
     * @exception  IOException  if an I/O error occurs.
     */
    public abstract int read() throws IOException;

In short from the api:

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

from InputStream.html#read()


system.in.read() method reads a byte and returns as an integer but if you enter a no between 1 to 9 ,it will return 48+ values because in ascii code table ,ascii values of 1-9 are 48-57 . hope , it will help.


System.in.read() reads from the standard input.

The standard input can be used to get input from user in a console environment but, as such user interface has no editing facilities, the interactive use of standard input is restricted to courses that teach programming.

Most production use of standard input is in programs designed to work inside Unix command-line pipelines. In such programs the payload that the program is processing is coming from the standard input and the program's result gets written to the standard output. In that case the standard input is never written directly by the user, it is the redirected output of another program or the contents of a file.

A typical pipeline looks like this:

# list files and directories ordered by increasing size
du -s * | sort -n

sort reads its data from the standard input, which is in fact the output of the du command. The sorted data is written to the standard output of sort, which ends up on the console by default, and can be easily redirected to a file or to another command.

As such, the standard input is comparatively rarely used in Java.


System.in.read() is a read input method for System.in class which is "Standard Input file" or 0 in conventional OS.


Just to complement the accepted answer, you could also use System.out.read() like this:

class Example {
    public static void main(String args[])
        throws java.io.IOException { // This works! No need to use try{// ...}catch(IOException ex){// ...}         

        System.out.println("Type a letter: ");
        char letter = (char) System.in.read();
        System.out.println("You typed the letter " + letter);
    }
}