Input/Output In Java

Note:- As hackerearth notes are going to be dissolved you can find this article here :-ArticleI/O is most important part of any programming language. Java has many ways to take input & post output. As from the title I am here to discuss about above three types of Input & Output.ScannerScanner is used to take formatted input as it break it into tokens and then parse that tokens into respective data types. It tokenize the string on the basis of Whitespaces by default which is space character. It is not synchronized so it is notThread-Safemeans multiple threads can produce unwanted results(refer Producer Consumer Problem). It usually parse the input which makes itslowand it have Buffer equals to 1K(1024bytes).It is simple than other I/O classes and a part ofjava.utilpackage. Let us understand by example:-class HackTheJava
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in); //Instantiation Of Scanner Object
int a=sc.nextInt(); //reads integer
double b=sc.nextDouble(); //reads double
String str=sc.nextLine(); //reads String
}
}BufferedReaderSince Unbuffered I/Os reads input which is handled by underlying Operating System. This is slow because each time it have to trigger disk access. To remove such overhead buffered I/O introduced in java. Buffer is memory in which data is to be stored. It is faster theScanneras it reads whole input as String throughreadLine()method and then we have to parse it into their respective data types. It is also Thread-safe.class HackTheJava
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine(); //reads String like 10<enter>
int a=Integer.parseInt(str) //reads integer
}
}Buffered Reader by default throwsIOExceptionwhich has to catch or throws further.Fast I/OAbove I/O are great but slow and it is too slow as I will show you later.Here you have to create your ownbufferand read input fromInputStreamdirectly throughread(byte[] b)method. Let us understand directly by example:-class Scan
{
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n==’-‘)
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>=’0’&&n<=’9’)
{
integer*=10;
integer+=n-‘0′;
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n==’-‘)
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!=’.’)
{
if(n>=’0’&&n<=’9′)
{
doub*=10;
doub+=n-‘0′;
n=scan();
}
else throw new InputMismatchException();
}
if(n==’.’)
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>=’0’&&n<=’9′)
{
temp/=10;
doub+=(n-‘0′)*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==’ ‘||n==’n’||n==’r’||n==’t’||n==-1)
return true;
return false;
}
}In above methodscan()we reading input as bytes throughread(byte[] b)method and return each Byte by increasingindex. ThenscanInt()return the inputted Integer.
Similarly for output you can useBufferedWriter.class Print
{
private final BufferedWriter bw;
public Print()
{
this.bw=new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object)throws IOException
{
bw.append(“”+object);
}
public void println(Object object)throws IOException
{
print(object);
bw.append(“n”);
}
public void close()throws IOException
{
bw.close();
}
}Now Check how fast is above method, Kindly see below link.http://www.codechef.com/status/FROGV,shivamsharmaFirst One & two is showing the least time in which above method is used with little difference. Third One is when reading input withScanobject but output withOutputStreamObject. And Fourth one is reading input fromScanobject and outputting bySystem.out.println(). And usingBufferedReader&ScannerYou will getTime Limit Exceed(TLE)error.emphasized text

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *