How to take input in Java

0

 Java is an object oriented programming language. In java there are two ways to take the input .


1. Scanner class 

2. BufferedReader class

We use these two classes to take input . Let's see these two one by one.


Scanner Class : It is most used class for the primitve data types. Basically it is text reader which parse the data to the primitive type . To use the Scanner  class we use import java.util.Scanner

Scanner class non-synchronous so it is not used in case of multiple threads . Let's take an example for the scanner class.



import java.util.Scanner;

class HindiCodingCommunity{

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

// To take the string input
String str = sc.nextLine();
System.out.println(str);

// To take the integer input
int intval = sc.nextInt();
System.out.println(intval);

// To take the float input
float floatval = sc.nextFloat();
System.out.println(floatval);
}
}


Input Types for Scanner :

nextBoolean() It reads a boolean value 

nextByte() It reads a byte value

nextDouble() It reads a double value 

nextFloat() It reads a float value

nextInt()         It reads a int value 

nextLine() It reads a String value 

nextLong() It reads a long value 

nextShort() It reads a short value 


BufferedReader Class : It is not mostly  used class for the primitve data types. It is used in case of Multiple threads .  To use the Buffered Reader class we use import java.io.*

Buffered Reader  class is synchronous so it is used in case of multiple threads . Also it is faster than the Scanner class . So Let's take an example for the Buffered Reader class.


import java.io.*;

class HindiCodingCommunity{

public static void main(String args[]) throws IOException{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// To take the string input
String str = br.readLine();
System.out.println(str);

// To take the integer input
int intval = Integer.parseInt(br.readLine());
System.out.println(intval);

// To take the float input
float floatval = Float.parseFloat(br.readLine());
System.out.println(floatval);
}
}


In this way we can take the input in Java.

If you want to write an article for us please send it to hindicodingcommunity@gmail.com 

Quocient and Remainder in Java

Intersection of two unsorted arrays in Java

Spiral Pattern of matrix in java

Snake pattern of matrix in java


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !