0% found this document useful (0 votes)
40 views

Basic Input and Output operations

The document provides an overview of input and output in Java, focusing on the System class, Scanner, BufferedReader, Console, and command-line arguments. It details methods for printing to the console, reading user input, and the advantages and disadvantages of each input method. Additionally, it includes sample code snippets and practice questions for better understanding.

Uploaded by

bharathkandhan96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Basic Input and Output operations

The document provides an overview of input and output in Java, focusing on the System class, Scanner, BufferedReader, Console, and command-line arguments. It details methods for printing to the console, reading user input, and the advantages and disadvantages of each input method. Additionally, it includes sample code snippets and practice questions for better understanding.

Uploaded by

bharathkandhan96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Basic input and output

OUTPUT
System Class

 The System class in Java is a part of the java.lang package and provides access to system-level resources
such as standard input, output, and error streams. It contains several static methods and fields, one of which is
out.

out Field
 System.out is a static member of the System class that refers to the standard output stream. By default, this
stream outputs data to the console. It is an instance of the PrintStream class, which handles text data display.

PrintStream Methods
The PrintStream class provides several methods for printing text, including:

 print(): Outputs the given text without adding a newline at the end.
 println(): Outputs the given text and moves the cursor to the next line (i.e., appends a newline character).
 printf(): Allows formatted output similar to printf in C, where you can format strings, integers, floating-point
numbers, etc.
OUTPUT
Common Printing Methods

 System.out.print(): Used for printing text or data without appending a newline.

System.out.print("Hello");
System.out.print("World");

// Output: HelloWorld

 System.out.println(): Prints the text followed by a newline.

System.out.println("Hello");
System.out.println("World");

// Output: // Hello // World

 System.out.printf(): Allows formatted printing similar to printf in C/C++.

System.out.printf("My age is %d years", 25);

// Output: My age is 25 years


OUTPUT
Escape Sequences

 In Java, certain characters are considered "escape sequences," which are used to represent non-
printing characters like newlines (\n), tabs (\t), and backslashes (\\).
 \n: Newline
 \t: Tab
 \\: Backslash Example:

System.out.println("Hello\nWorld");

// Output: // Hello // World

Why Use System.out?


 The System.out stream is primarily used for debugging purposes or displaying results in console-based
programs. In graphical user interface (GUI) applications, this method is rarely used as GUI frameworks
have their own methods for outputting data to windows and dialogs.
 These printing methods are commonly used when running Java applications in a
command-line interface (CLI) or for basic debugging during development.
INPUT
 In Java, taking input from the user is commonly done using the Scanner class, which is part of the java.util package.
However, there are other methods available as well, such as using BufferedReader or Console.

Using the Scanner Class


 The Scanner class is one of the most commonly used classes for getting user input. It allows you to take input of
various data types like int, float, double, String, etc.

Steps to use Scanner:


 Import the java.util.Scanner package.
 Create a Scanner object.
 Use the appropriate method to get input from the user.

Common Methods in Scanner:

 nextInt(): Reads an integer.


 nextDouble(): Reads a double.
 nextBoolean(): Reads a boolean.
 nextLine(): Reads a line of text.
 next(): Reads a single word (stops at space or newline).
 nextFloat(), nextLong(), etc.: Reads other data types like float, long, etc.
INPUT
Scanner Considerations:
 Newline issue: When you use methods like nextInt() or nextDouble(), the newline character (\n) is not consumed. To
solve this, you can call scanner.nextLine() after such inputs to consume the remaining newline.

Advantages:

 Simple to use for basic input tasks.


 Supports input of different types.

Disadvantages:

 Not the most efficient for large-scale input as it involves tokenizing.


 Needs proper handling of newline characters between inputs.
INPUT
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object to take input from the console
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");
int num = scanner.nextInt(); // Reading an integer

System.out.println("Enter a double: ");


double decimal = scanner.nextDouble(); // Reading a double

System.out.println("Enter a string: ");


scanner.nextLine(); // To consume the newline character left by nextDouble()
String str = scanner.nextLine(); // Reading a string (including spaces)

// Output the inputs


System.out.println("Integer: " + num);
System.out.println("Double: " + decimal);
System.out.println("String: " + str);
// Close the scanner to prevent resource leaks
scanner.close();
}
}
INPUT
Using BufferedReader Class
 BufferedReader is a part of the java.io package and is more efficient than Scanner for reading larger amounts of
data, as it buffers input. It reads input as a string, so you’ll need to manually parse the input into other data types if
needed.

Steps to use BufferedReader:


 Import java.io.BufferedReader and java.io.InputStreamReader.
 Wrap InputStreamReader inside a BufferedReader object.
 Use the readLine() method to read input as a string.

Key Methods in BufferedReader:


 readLine(): Reads a line of text as a string.

Advantages:
 More efficient for reading large blocks of input.
 Good for reading line-based input (e.g., reading from files).

Disadvantages:
 All input is read as a string, so parsing is necessary if you need other data types.
 Needs exception handling because readLine() throws IOException.
INPUT
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
// Create BufferedReader object
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
// 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());//Need to parse string input into an integer
// Output the inputs
System.out.println("String: " + str);
System.out.println("Integer: " + num);
} catch (IOException e) {
System.out.println("Error reading input: " + e.getMessage());
}
}
}
INPUT
Using the Console Class
 The Console class is used for secure input, especially when you want to mask input (such as passwords). It’s part of the
java.io package and is available only when running the program from a console or command-line environment.

Steps to use Console:


 Obtain a Console object using System.console().
 Use the readLine() or readPassword() methods to read input.

Key Methods in Console:


 readLine(): Reads a line of text.
 readPassword(): Reads input as a character array and masks the input (commonly used for passwords).

Advantages:
 Allows secure input for sensitive data like passwords.
 Avoids the newline issue found in Scanner.

Disadvantages:
 Only works in a real console environment (not available in some IDEs like Eclipse or IntelliJ).
INPUT
import java.io.Console;
public class Main
{
public static void main(String[] args) {
// Get the system console
Console console = System.console();

if (console != null) {
// Reading a line of input
String name = console.readLine("Enter your name: ");

// Reading a password securely (input will be masked)


char[] password = console.readPassword("Enter your password: ");

// Output the inputs


System.out.println("Name: " + name);
System.out.println("Password: " + new String(password));
} else {
System.out.println("Console not available");
}
}
}
INPUT
Using Command-Line Arguments
 Command-line arguments are another way to pass input to a Java program. These are passed when the program is
executed, and you can access them via the String[] args parameter of the main() method.

Key Points:
 args[0], args[1], etc., contain the command-line arguments passed when running the program.
 You need to convert the string arguments into appropriate types if needed (e.g., using Integer.parseInt() for integers).

Advantages:
 Useful for passing configuration options or parameters without prompting the user during runtime.

Disadvantages:
 Requires user to run the program with specific arguments at the command line.
INPUT
public class Main
{
public static void main(String[] args)
{
if (args.length > 0)
{
// Output command-line arguments
System.out.println("First argument: " + args[0]);
}
else
{
System.out.println("No arguments passed.");
}
}
}
INPUT
Method Class Use Case Advantages Disadvantages

Easy to use, supports Not very efficient, newline


Scanner java.util.Scanner General-purpose input
multiple data types issues between inputs

Requires manual
Efficient reading of large Fast, can handle large
BufferedReader java.io.BufferedReader parsing, needs exception
text input blocks of input
handling

Works only in console


Secure input, especially Allows secure input (e.g.,
Console java.io.Console environments, not in all
passwords passwords)
IDEs

Input passed during Useful for configuration Input cannot be changed


Command-line args String[] args
program execution or initial parameters after program starts
INPUT
Practice Questions:
 java_IP_L0_1.Print the following output: Print the following output : Let's learn 'JAVA'
together with MySlate Team
 java_IP_L0_2,Print the following output:Print the following output : Success is when your
"signature" becomes "autograph"
 java_IP_L0_3.Print the following output: \n
 java_IP_L0_4.Print the following output: %%
 java_IP_L0_5.Print the following output :\
 java_IP_L0_6.Read n Print Integer
 java_IP_L0_7.Print Character
 java_IP_L0_8.Initialize values: A = 10 , B = 20
 java_IP_L0_9,Width Space: 25 , 98
00025
98
 java_IP_L0_10.Print the number along with its sign
THANK YOU

You might also like