sanchit bhutani
sanchit bhutani

Reputation: 61

can anyone tell me what is the difference between read() and readline();?

package com.learn.java;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferReaderInput {

    public static void main(String[] args) throws IOException {
        BufferedReader bufferreaderIn = new BufferedReader(
                new InputStreamReader(System.in));
        System.out.println("Enter your Name");
        String Name = bufferreaderIn.readLine();

        System.out.println("Enter your age");
        int age = Integer.parseInt(bufferreaderIn.readLine());

        System.out.println("Enter your salary");
        int sal = bufferreaderIn.read();

        System.out.println("Hi, I'm " + Name + " my age is " + age
                + " and my salary is " + sal);
    }

}

When I enter salary using obj.read(); it is not giving the right output.

With that can anyone tell me what is the difference between read() and readline()?

Upvotes: 3

Views: 8433

Answers (2)

skypjack
skypjack

Reputation: 50540

As from the documentation of BufferedReader, we have this for read:

Reads a single character.

And this for readLine:

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

So, set apart the details of when a line is considered to be terminated, the difference is that the first one read a single character whilst the second one read a whole line.

Upvotes: 3

pahan
pahan

Reputation: 567

readLine() reads line till it sees \n, \r or \r\n, while read() read one character.

Upvotes: 2

Related Questions