Contents
Input/Output in Java
How to Take Input from User in Java
Java provides multiple ways to take input from users through its I/O (Input/Output) package. These streams facilitate the reading of characters, data types, and objects from input devices such as keyboards or files. The most common ways to capture user input in Java are through the BufferedReader class and the Scanner class.
Methods to Take Input in Java
There are two primary ways to get input from the user or a file in Java:
1. Using BufferedReader Class
2. Using Scanner Class
1. Using BufferedReader Class to Take Input in Java
The BufferedReader class is part of Java’s I/O package and is used for reading streams of characters. The readLine()
method of this class reads input as a string. InputStreamReader is often used in conjunction with BufferedReader to convert byte streams into character streams, enabling character-based input reading.
Note: BufferedReader can throw checked exceptions, which need to be handled using try-catch
blocks or by declaring them with throws
.
Example of Taking Input Using BufferedReader:
import java.io.*;
public class InputExample {
public static void main(String[] args) throws IOException {
// Creating a BufferedReader object
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Reading string input
System.out.println("Enter a string:");
String str = reader.readLine();
// Reading integer input
System.out.println("Enter an integer:");
int num = Integer.parseInt(reader.readLine());
// Output the values
System.out.println("Entered String: " + str);
System.out.println("Entered Integer: " + num);
}
}
Output:
Enter a string:
John Doe
Enter an integer:
123
Entered String: John Doe
Entered Integer: 123
Alternative Example of BufferedReader Input:
import java.io.*;
public class Example {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter your name:");
String name = reader.readLine(); // Reading string input
System.out.println("Name: " + name);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Sample Output:
Enter your name:
John
Name: John
2. Using Scanner Class for Taking Input in Java
The Scanner class is an advanced and user-friendly input class that is part of Java’s util
package. It simplifies input handling by providing various methods like nextInt()
, nextFloat()
, next()
, and nextLine()
. These methods allow you to directly capture input without explicit parsing.
Advantages of Scanner:
- Easier to use than BufferedReader.
- Supports multiple data types (integers, floats, strings, etc.) directly.
- No need for
throws
declarations as no checked exceptions are thrown. - Provides methods to read formatted input easily.
Example of Taking Input Using Scanner:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// Create Scanner object
Scanner sc = new Scanner(System.in);
// Input a String (single word)
String word = sc.next();
System.out.println("Entered word: " + word);
// Input a String (full sentence)
sc.nextLine(); // Clear the buffer
String sentence = sc.nextLine();
System.out.println("Entered sentence: " + sentence);
// Input an Integer
int num = sc.nextInt();
System.out.println("Entered Integer: " + num);
// Input a floating-point number
float f = sc.nextFloat();
System.out.println("Entered Float: " + f);
}
}
Output:
John
Hello World
123
45.67
Entered word: John
Entered sentence: Hello World
Entered Integer: 123
Entered Float: 45.67
Another Example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Enter your roll number:");
int rollNo = sc.nextInt();
System.out.println("Enter your marks:");
float marks = sc.nextFloat();
// Output the entered data
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNo);
System.out.println("Marks: " + marks);
}
}
Output:
Enter your name:
Alice
Enter your roll number:
10
Enter your marks:
89.5
Name: Alice
Roll Number: 10
Marks: 89.5
Differences Between BufferedReader and Scanner
1. BufferedReader is a basic way to read input, typically used for reading streams of characters. It is faster than Scanner as it doesn’t perform any post-processing or parsing.
2. Scanner is more user-friendly for simple input, especially when you need to read different data types. However, Scanner is slower because it performs input parsing internally (like nextInt(), nextFloat()).
3. BufferedReader allows you to specify the size of the input stream to be read, making it more flexible when handling large input.
4. BufferedReader is synchronized, making it suitable for multi-threaded applications, while Scanner is not.
5. Scanner is typically preferred for smaller inputs due to its simplicity, while BufferedReader is favored for larger inputs due to better performance.
Scanner Class in Java
The Scanner
class in Java is part of the java.util
package and is used to obtain input from the user, including primitive data types like int
, double
, and boolean
, as well as strings.
While the Scanner
class is the simplest way to read input, it’s not the most efficient when performance is critical, such as in competitive programming, due to additional overhead.
Input Types in Java Scanner
The Scanner
class can take various types of input from the user. Some of the commonly used methods for extracting data from an input stream are listed below:
Method | Description |
---|---|
nextBoolean() | Reads a Boolean value |
nextByte() | Reads a Byte value |
nextDouble() | Reads a Double value |
nextFloat() | Reads a Float value |
nextInt() | Reads an Integer value |
nextLine() | Reads an entire line as a String |
nextLong() | Reads a Long value |
nextShort() | Reads a Short value |
Example 1: Reading Data of Various Types
Below is a sample code that demonstrates how to read different types of data using the Scanner
class.
// Java program to read data of various types using Scanner class.
import java.util.Scanner;
public class ScannerDemo1 {
public static void main(String[] args) {
// Creating a Scanner object for input
Scanner sc = new Scanner(System.in);
// Reading a String input
String name = sc.nextLine();
// Reading a Character input
char gender = sc.next().charAt(0);
// Reading numerical data
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();
// Outputting the values to check input
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Age: " + age);
System.out.println("Mobile Number: " + mobileNo);
System.out.println("CGPA: " + cgpa);
}
}
Input:
Alice
F
25
9876543210
8.9
Output:
Name: Alice
Gender: F
Age: 25
Mobile Number: 9876543210
CGPA: 8.9
Checking Input Type with hasNextXYZ()
Methods
In some cases, we need to verify the type of the next input or whether the input has ended (e.g., when encountering the EOF marker). The hasNextXYZ()
methods allow us to check if the next token is of the desired type. Here, XYZ
represents the data type of interest.
For instance, we can check for an integer using hasNextInt()
or a string using hasNextLine()
. Similarly, to check for a single character, we can use hasNext().charAt(0)
.
Example 2: Calculating the Mean of Numbers
// Java program to read values using Scanner and calculate their mean.
import java.util.Scanner;
public class ScannerDemo2 {
public static void main(String[] args) {
// Initialize Scanner object
Scanner sc = new Scanner(System.in);
// Initialize sum and count variables
int sum = 0, count = 0;
// Read integers until non-integer input is encountered
while (sc.hasNextInt()) {
int num = sc.nextInt();
sum += num;
count++;
}
// Calculate and print the mean
if (count > 0) {
int mean = sum / count;
System.out.println("Mean: " + mean);
} else {
System.out.println("No integers were input. Mean cannot be calculated.");
}
}
}
Input:
1 2 3 4 5
Output:
Mean: 3
Key Points About the Scanner Class
1. Creating a Scanner Object: To create a Scanner object, we usually pass the predefined System.in object, which represents standard input. We can also pass a File object to read input from a file.
2. Reading Numerical Values: For each primitive data type, there is a corresponding nextXYZ() method to read its value. For example, nextShort() reads a short value, and nextInt() reads an int.
3. Reading Strings: To read strings, we use nextLine(). This method reads the entire line until a newline character is encountered.
4. Reading a Single Character: To read a single character, we can use next().charAt(0). The next() method reads the next token (a word or symbol), and charAt(0) returns the first character of that token.
5. How Scanner Reads Input: The Scanner class reads an entire line and divides it into tokens. Each token represents a meaningful piece of the input. For example, if the input string is “Hello world”, the Scanner object will treat “Hello” and “world” as two separate tokens, and we can iterate over these tokens using its various methods.
Ways to read input from console in Java
In Java, there are several ways to read input from the user in the command-line environment. Here are five methods:
1. Using BufferedReader
Class
The BufferedReader
class is the traditional way to take input, introduced in JDK 1.0. It wraps the standard input stream (System.in
) in an InputStreamReader
, which is further wrapped in a BufferedReader
for efficient reading of input.
Key Points:
- Input is buffered for performance.
- Syntax can be a bit more complex compared to newer methods.
Example:
// Java program to demonstrate BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
// Using BufferedReader to get input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Reading a string input
String name = reader.readLine();
// Printing the input
System.out.println(name);
}
}
Input:
John
Output:
John
2. Using Scanner Class
The Scanner
class, introduced in JDK 1.5, is one of the most commonly used methods to read input. It can parse primitive types and strings using regular expressions.
Advantages:
- Simplifies reading primitive types like
int
,float
, and more. - Regular expressions can be used to tokenize input.
Example:
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
// Create Scanner object
Scanner scn = new Scanner(System.in);
// Read a single word as a string
System.out.println("Enter a word:");
String word = scn.next();
// Read a full line as a string
System.out.println("Enter a sentence:");
scn.nextLine(); // consume the leftover newline
String sentence = scn.nextLine();
// Read an integer
System.out.println("Enter an integer:");
int number = scn.nextInt();
// Read a float value
System.out.println("Enter a floating point number:");
float decimal = scn.nextFloat();
// Display the inputs
System.out.println("Word: " + word);
System.out.println("Sentence: " + sentence);
System.out.println("Integer: "
Input:
Alice
25
4.5
Output:
You entered string: Alice
You entered integer: 25
You entered float: 4.5
3. Using Console
Class
Introduced in JDK 1.6, the Console
class is useful for reading input from the command line, especially for secure inputs like passwords (where input isn’t displayed). However, it may not work in non-interactive environments like IDEs.
Advantages:
- Can hide input (useful for password entry).
- Supports formatted input and output.
Example:
// Java program to demonstrate Console class
public class Sample {
public static void main(String[] args) {
// Using Console to get input
String name = System.console().readLine();
System.out.println("You entered string: " + name);
}
}
Input:
Michael
Output:
You entered string: Michael
4. Using Command-Line Arguments
This method uses the command-line arguments passed to the program at runtime. The arguments are stored as strings in the args[]
array, and can be converted to other data types using methods like Integer.parseInt()
.
Example:
// Program to demonstrate command-line arguments
class Hello {
public static void main(String[] args) {
// Check if arguments were passed
if (args.length > 0) {
System.out.println("The command line arguments are:");
// Loop through the args array
for (String val : args)
System.out.println(val);
} else {
System.out.println("No command line arguments found.");
}
}
}
Command Line Arguments:
java Hello John Doe
Output:
The command line arguments are:
John
Doe
5. Using DataInputStream
Class
The DataInputStream
class allows reading primitive data types and strings from an input stream in a machine-independent way. This class is useful when working with binary input/output, and it was introduced in JDK 1.0.
Key Points:
- Reads binary data in a machine-independent format.
- Often used with
DataOutputStream
for consistent data handling.
Example:
// Java program to demonstrate DataInputStream
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
DataInputStream reader = new DataInputStream(System.in);
// Reading an integer input
System.out.print("Enter an integer: ");
int inputInt = Integer.parseInt(reader.readLine());
// Reading a string input
System.out.print("Enter a string: ");
String inputString = reader.readLine();
// Output the input values
System.out.println("You entered integer: " + inputInt);
System.out.println("You entered string: " + inputString);
}
}
Input:
Enter an integer: 30
Enter a string: Java Programming
Output:
You entered integer: 30
You entered string: Java Programming
Java System.out.println()
The System.out.println()
method is used in Java to print a message or value to the console. It is a commonly used function that prints any argument passed to it, followed by a new line.
Breakdown of System.out.println()
The statement can be split into three parts for better understanding:
1. System: This is a final class from the java.lang package.
2. out: A static member of the System class, which is an instance of the PrintStream class.
3. println(): A method of the PrintStream class that prints the passed argument and adds a newline character at the end. It’s an enhanced version of print() that automatically moves the cursor to the next line.
Syntax:
System.out.println(parameter);
Example of System.out.println()
Example : Basic Output
public class Example {
public static void main(String[] args) {
System.out.println("Hello");
System.out.println("World");
System.out.println("Java Programming");
}
}
Output:
Hello
World
Java Programming
Java’s Other Standard Streams
- System.in: The standard input stream used for reading input from the keyboard.
- System.err: The standard error stream used to display error messages.
Example:
System.err.print("This is an error message");
Overloads of println()
Method
Java supports method overloading, allowing multiple methods with the same name but different parameter types. PrintStream
provides various overloads of the println()
method for different data types.
Example of Overloaded println()
Methods
public class Example {
public static void main(String[] args) {
int num = 15;
char letter = 'A';
String text = "Java";
double decimal = 25.78;
float floatNum = 10.5f;
boolean flag = true;
// Various overloaded versions of println()
System.out.println(); // Prints an empty line
System.out.println(num);
System.out.println(letter);
System.out.println(text);
System.out.println(decimal);
System.out.println(floatNum);
System.out.println(flag);
}
}
Output:
15
A
Java
25.78
10.5
true
Difference Between System.out.print()
and System.out.println()
System.out.print()
: Prints the provided text or value on the console and keeps the cursor on the same line.System.out.println()
: Prints the provided text or value, and moves the cursor to the next line.
Example:
public class Example {
public static void main(String[] args) {
System.out.println("Using print():");
// Using print()
System.out.print("Hello ");
System.out.print("World ");
System.out.print("Java");
System.out.println(); // Moving to the next line
System.out.println("Using println():");
// Using println()
System.out.println("Hello");
System.out.println("World");
System.out.println("Java");
}
}
Output:
Using print():
Hello World Java
Using println():
Hello
World
Java
Formatted Output in Java using printf()
In programming, it is often necessary to display output in a specific format. Java’s printf()
method, similar to the C language’s printf
, allows formatting of output using format specifiers. In this article, we’ll cover different ways to format output in Java using printf()
.
Formatting Using printf()
printf()
uses format specifiers to format different data types. The commonly used data types for formatting are:
1. Number Formatting
2. Decimal Number Formatting
3. Boolean Formatting
4. Character Formatting
5. String Formatting
6. Date and Time Formatting
1. Number Formatting
For formatting integers (like int
, long
), the format specifier used is %d
.
Example:
public class Example {
public static void main(String[] args) {
int number = 10000;
// Format with commas separating thousands
System.out.printf("%,d%n", number);
}
}
Output:
10,000
2. Decimal Number Formatting
To format decimal numbers, we use the %f
specifier.
Example:
public class Example {
public static void main(String[] args) {
double pi = 3.14159265359;
// Formatting decimal numbers
System.out.printf("%f\n", pi);
System.out.printf("%5.3f\n", pi);
System.out.printf("%5.2f\n", pi);
}
}
Output:
3.141593
3.142
3.14
3. Boolean Formatting
Boolean values can be formatted using %b
or %B
.
Example:
public class Example {
public static void main(String[] args) {
boolean boolTrue = true;
boolean boolFalse = false;
Integer nullValue = null;
System.out.printf("%b\n", boolTrue); // true
System.out.printf("%B\n", boolTrue); // TRUE
System.out.printf("%b\n", boolFalse); // false
System.out.printf("%B\n", nullValue); // FALSE
}
}
Output:
true
TRUE
false
FALSE
4. Character Formatting
Character formatting is done using the %c
or %C
specifiers.
Example:
public class Example {
public static void main(String[] args) {
char character = 'a';
System.out.printf("%c\n", character); // a
System.out.printf("%C\n", character); // A (uppercase)
}
}
Output:
a
A
5. String Formatting
Strings are formatted using %s
or %S
.
Example:
public class Example {
public static void main(String[] args) {
String text = "java programming";
System.out.printf("%s\n", text); // java programming
System.out.printf("%S\n", text); // JAVA PROGRAMMING
}
}
Output:
java programming
JAVA PROGRAMMING
6. Date and Time Formatting
Formatting date and time is more complex and requires specific knowledge of format specifiers such as %tT
, %tH
, %tM
, etc.
Example:
import java.util.Date;
public class Example {
public static void main(String[] args) {
Date currentTime = new Date();
System.out.printf("Current Time: %tT\n", currentTime); // Full time format
System.out.printf("Hours: %tH Minutes: %tM Seconds: %tS\n",
currentTime, currentTime, currentTime); // Individual components
// Time with AM/PM, milliseconds, nanoseconds, and time zone
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz%n", currentTime);
}
}
Output:
Current Time: 11:32:36
Hours: 11 Minutes: 32 Seconds: 36
11:32:36 am 198 198000000 +0000
Other Methods for Formatting
1. Decimal Formatting using DecimalFormat
DecimalFormat
can be used to format numbers with various patterns.
Example:
import java.text.DecimalFormat;
public class DecimalFormatting {
public static void main(String[] args) {
double num = 123.4567;
// Formatting without fraction part
DecimalFormat df = new DecimalFormat("####");
System.out.println("Without fraction part: " + df.format(num));
// Formatting to 2 decimal places
df = new DecimalFormat("#.##");
System.out.println("Formatted to 2 decimal places: " + df.format(num));
// Formatting with appended zeroes
df = new DecimalFormat("#.000000");
System.out.println("With appended zeroes: " + df.format(num));
// Formatting with leading zeroes
df = new DecimalFormat("00000.00");
System.out.println("With leading zeroes: " + df.format(num));
// Formatting currency
double income = 23456.789;
df = new DecimalFormat("$###,###.##");
System.out.println("Formatted income: " + df.format(income));
}
}
Output:
Without fraction part: 123
Formatted to 2 decimal places: 123.46
With appended zeroes: 123.456700
With leading zeroes: 00123.46
Formatted income: $23,456.79
2. Formatting Dates using SimpleDateFormat
SimpleDateFormat
allows date formatting based on custom patterns.
Example:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatting {
public static void main(String[] args) {
// Formatting date to 'dd-MM-yyyy'
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = sdf.format(new Date());
System.out.println("Formatted Date: " + formattedDate);
// Parsing a string date
String dateStr = "02/18/1995";
sdf = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = sdf.parse(dateStr);
System.out.println("Parsed Date: " + date);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Formatted Date: 03-10-2024
Parsed Date: Sat Feb 18 00:00:00 UTC 1995
3. Static Variables
Static variables are shared across all instances of a class and are declared with the static
keyword. Only one copy of a static variable exists, regardless of how many objects are created.
// Example of static variables
public class StaticVariableExample {
public static String company = "TechCorp"; // Static variable
public static void main(String[] args) {
System.out.println("Company: " + StaticVariableExample.company); // Accessing without object
}
}
Output:
Company: TechCorp
Java Variables
In Java, the scope of a variable refers to the region in the code where the variable is accessible. Java has lexical (static) scoping, meaning the scope of a variable is determined at compile time and is not dependent on the function call stack. The scope rules in Java can be broadly classified into three categories based on where the variables are declared.
1. Member Variables (Class-Level Scope)
2. Local Variables (Method-Level Scope)
3. Block Variables (Loop or Block-Level Scope)
1. Member Variables (Class-Level Scope)
Member variables are declared inside a class but outside any method, constructor, or block. They can be accessed anywhere within the class and can have different access levels (e.g., public
, private
, protected
, or default). Access to member variables outside the class depends on the access modifier used.
Example:
public class Test {
// Member variables
int a; // Default access modifier
private String b; // Private member variable
char c; // Default access modifier
void method1() {
// Member variables can be accessed here
System.out.println(a);
System.out.println(b);
}
int method2() {
return a;
}
}
- Public: Accessible within the class, in subclasses, and outside the class.
- Protected: Accessible within the class and in subclasses but not outside the package.
- Default (no modifier): Accessible within the same package but not outside it.
- Private: Only accessible within the class.
2. Local Variables (Method-Level Scope)
Local variables are declared inside a method or constructor and are only accessible within that method. They must be initialized before use, and their lifetime is limited to the method’s execution. Once the method finishes, local variables are destroyed.
Example:
public class Test {
void method1() {
// Local variable
int x = 10;
System.out.println(x); // Accessible inside the method
}
public static void main(String[] args) {
Test t = new Test();
t.method1();
}
}
Local variables do not retain their values once the method completes, and they are recreated each time the method is invoked.
3. Block Variables (Loop or Block-Level Scope)
Variables declared inside a block (within curly braces {}
) are only accessible within that block. Once the block is exited, these variables are out of scope and cannot be accessed. This applies to variables declared inside loops or conditionals.
Example of Block-Level Scope:
public class Test {
public static void main(String[] args) {
{
int x = 10; // x is only accessible inside this block
System.out.println(x);
}
// Uncommenting the following line will cause an error
// System.out.println(x); // x is out of scope here
}
}
Loop Variables (Block Scope)
Variables declared inside a loop have scope limited to the loop. They cannot be accessed outside the loop.
Example:
class Test {
public static void main(String[] args) {
for (int x = 0; x < 4; x++) {
System.out.println(x); // x is accessible inside the loop
}
// Uncommenting the following line will result in an error
// System.out.println(x); // x is out of scope here
}
}
If you need to access a loop variable outside the loop, declare it before the loop:
class Test {
public static void main(String[] args) {
int x;
for (x = 0; x < 4; x++) {
System.out.println(x);
}
System.out.println(x); // x is accessible outside the loop
}
}
Output:
0
1
2
3
4
Loop Variable Scope with Overlapping Names
In Java, you cannot declare two variables with the same name within the same scope. However, in languages like C++, it’s possible to have the same variable name in nested scopes, which is not allowed in Java.
Incorrect Example in Java (compilation error):
class Test {
public static void main(String[] args) {
int a = 5;
for (int a = 0; a < 5; a++) { // Error: Variable 'a' is already defined
System.out.println(a);
}
}
}
Output:
Error: variable 'a' is already defined
Valid Example with Loop Variable Declaration After Loop
To avoid such errors, you can declare a variable outside the loop and use it after the loop finishes.
Example:
class Test {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i); // Loop variable i
}
int i = 20; // Declare i after the loop
System.out.println(i); // Access new i outside the loop
}
}
Output:
1
2
3
4
5
6
7
8
9
10
20