Page 328 - CITS - Computer Software Application -TT
P. 328
COMPUTER SOFTWARE APPLICATION - CITS
In this example
• %s is a placeholder for a string (name).
• %d is a placeholder for an integer (age).
• %.2f is a placeholder for a floating-point number (salary) with 2 decimal places.
The %n is used to insert a platform-independent line separator.
Types of Streams
Streams can be categorised into two main classes based on the type of operations they are used for
1 Input Stream: These streams are employed to retrieve data as input from various sources such as arrays, files,
or peripheral devices. Examples include FileInputStream, BufferedInputStream, and ByteArrayInputStream
2 Output Stream: These streams are used to write data as output to various destinations such as arrays,
files, or output peripheral devices. Examples include FileOutputStream, BufferedOutputStream, and
ByteArrayOutputStream
Input using Scanner class and Console class methods
In Java, you can use the Scanner class and the Console class to interact with the user via the command line for
input and output. Here are examples of how to use both classes for input:
Scanner class
In Java, the Scanner class from the java.util package is employed for acquiring input of primitive types such as
int, double, as well as strings.
While using the Scanner class is the simplest method for reading input in a Java program, it may not be the most
efficient choice for situations where input processing time is critical, such as competitive programming.
Syntax
Scanner sc=new Scanner(System.in);
Methods of Java Scanner Class
• nextBoolean(): Used for reading a Boolean value.
• nextByte(): Used for reading a Byte value.
• nextDouble(): Used for reading a Double value.
• nextFloat(): Used for reading a Float value.
• nextInt(): Used for reading an Int value.
• nextLine(): Used for reading a Line value (usually a String).
• nextLong(): Used for reading a Long value.
• nextShort(): Used for reading a Short value.
“Let’s examine a code snippet that demonstrates how to read input of various data types.”
Example
// Java program to read data of various types using Scanner
// class.
import java.util.Scanner;
public class ScannerDemo1 {
public static void main(String[] args)
{
315
CITS : IT&ITES - Computer Software Application - Lesson 78 - 84
78