0% found this document useful (0 votes)
3 views9 pages

Java Module 1 4

The document provides a comprehensive overview of input and output statements in Java, comparing them to their C language equivalents. It details formatted and unformatted I/O methods, including the use of the Scanner class for reading input and System.out for outputting data. Additionally, it explains format specifiers, control codes, and nuances related to reading strings and characters in Java.

Uploaded by

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

Java Module 1 4

The document provides a comprehensive overview of input and output statements in Java, comparing them to their C language equivalents. It details formatted and unformatted I/O methods, including the use of the Scanner class for reading input and System.out for outputting data. Additionally, it explains format specifiers, control codes, and nuances related to reading strings and characters in Java.

Uploaded by

nagadhanush700
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INPUT AND OUTPUT

STATEMENTS

Java Fundamentals | Module 1.4


INPUT AND OUTPUT STATEMENTS

Standard Input and Output

Formatted I/O Unformatted I/O

Input Function Output Function Input Function Output Function

Scanner [Link]() [Link] [Link]() BufferedReader [Link]


.print/println/printf .print(char)

C → Java equivalent mapping:


printf() → [Link]() / println() | scanf() → [Link]() / nextLine() | getchar() → [Link]()
[Link] – OUTPUT METHODS
Java's primary output class: [Link] (a PrintStream object)
Must import nothing – [Link] is automatically available.

Method Description Example

[Link](x) Prints x without newline [Link]("Hello");

[Link](x) Prints x followed by newline [Link]("Hello");

[Link](fmt, args) Formatted output (like C printf) [Link]("%d", 42);

[Link](fmt, args)
printf() / format() – Format Specifiers: Same as printf() [Link]("%.2f", 3.14);

Code Variable Type Display Control Codes (Escape Sequences)

%c char single character Sequence Meaning

%d (%i) int signed integer


\b Backspace
%e (%E) float/double exponential format
\f Form feed
%f float/double signed decimal
\n New line
%g (%G) float/double shorter of %f or %e
\r Carriage return
%o int unsigned octal
\t Horizontal tab
%s String sequence of characters
\' Single quote
%n — newline (platform-independent)
\" Double quote
%b boolean true or false
\\ Backslash
%x (%X) int unsigned hex value
\0 Null
%% — literal % character
printf() – FORMAT SPECIFIERS WITH MODIFIERS
Format specifier structure: % [flags] [width] [.precision] [size] conversion_code

% Flag Min width Precision Size Conv code

* – + 0 # number .number h l L d i u o x c s f e g

Flags: Output Examples:


[Link]("%3d",10); → ' 10'

Flag Meaning
[Link]("%6d",10); → ' 10'

– Left-justify the display (default is right-justified)


[Link]("%-6d",10); → '10 '
+ Display positive or negative sign of value
[Link]("%06d",10); → '000010'
space Display space if there is no sign

[Link]("%+6d",10); → ' +10'


0 Pad with leading zeros

# Use alternate form of specifier [Link]("%7.2f",5.43); → ' 5.43'

[Link]("%.2f",5.43); → '5.43'
Size Modifiers:
[Link]("%09.2f",523.75); → '000523.75'

Size modifier Conv code Converts to [Link]("%e",523.75); → '5.237500e+02'

l d i o u x long int
[Link]("%g",523.75); → '523.75'

h d i o u x short int

l e f double Note: If precision is not specified, default of 6 is assumed for floats.

L e f long double
[Link]() – RETURN VALUE & EXAMPLES
printf() returns the number of characters successfully written. format() returns the formatted string.

import [Link].*;
public class PrintfReturn {
public static void main(String[] args) {
// printf returns number of chars printed
Output:
int count = [Link]("Hello, World!%n").toString().length();
// Better way – use [Link]() to get the string first Hello, World!
String s = [Link]("Hello, World!%n");
[Link]("String length: %d%n", [Link]()); String length: 14
}
}

float a = 20.5666666f;
double b = 20.5666666; Output:
int c = 12;
20.566668
[Link]("%f%n", a); // 20.566668 (float rounding) 20.566667
[Link]("%f%n", b); // 20.566667 (double more precise)
[Link]("%g%n", a); // 20.5667 20.5667
[Link]("%e%n", a); // 2.056667e+01
2.056667e+01
[Link]("%o%n", c); // 14 (octal of 12)
[Link]("%x%n", c); // c (hex of 12) 14
[Link]("%b%n", true); // true
c
[Link]("%10s%n", "Hi"); // ' Hi'
true

Hi
Note: float has less precision than double – use double for full decimal accuracy.
Scanner CLASS – FORMATTED INPUT (scanf equivalent)
Scanner ([Link]) reads formatted data from keyboard, files, or strings.
Syntax:
Scanner sc = new Scanner([Link]);

Method Return Type Description (C scanf equivalent)

[Link]() int Reads next int (like %d in scanf)

[Link]() long Reads next long

[Link]() float Reads next float (like %f)

[Link]() double Reads next double

[Link]() String Reads next token (no spaces)

[Link]() String Reads full line incl. spaces

[Link]() boolean Reads true or false

[Link]() byte Reads next byte

[Link]() short Reads next short


import [Link];
public class ScannerDemo {
public static void main(String[] args) { Sample Output:
Scanner sc = new Scanner([Link]);
Name: Alice Age: 20 GPA: 3.90
[Link]("Enter name: ");
String name = [Link](); // reads full line
[Link]("Enter age: ");
int age = [Link](); // reads integer
[Link]("Enter GPA: ");
double gpa = [Link](); // reads double
[Link]("Name: %s Age: %d GPA: %.2f%n",
name, age, gpa);
[Link](); // close scanner when done
}
}
nextLine() after nextInt() Scanner – IMPORTANT NUANCES
After reading int/double, a stray newline remains in the buffer.
Call [Link]() once to consume it before reading a String.

Reading strings with spaces


[Link]() stops at whitespace.
Use [Link]() to read full lines including spaces.

Scanner returns value


[Link]() returns true if next token is an int.
Useful for input validation loops.

Delimiter
Default delimiter is whitespace.
Customise: [Link](",") for CSV input.

Scanner sc = new Scanner([Link]);


int age = [Link]();
UNFORMATTED I/O – Character-Level Input/Output

Handle one character at a time.

[Link]() does NOT require Enter to be pressed first (low-level, like getch()).

For output, [Link](char) displays a single character on the console.


getchar() / putchar() → Java getchar()/putchar() Sample Code

// getchar() equivalent import [Link].*;


int ch = [Link](); // reads one char as int public class CharIO {
// On EOF returns -1 public static void main(String[] args)
throws IOException {
// putchar() equivalent int ch;
[Link]((char) ch); // cast int back to char ch = 'A';
[Link]((char) ch); // A
}
}

// Convert lowercase to uppercase gets() / puts() → Java equivalent:


import [Link].*;
// gets() equivalent (read full line):
public class ToUpper {
Scanner sc = new Scanner([Link]);
public static void main(String[] args)
String line = [Link]();
throws IOException {
int ch = [Link](); // puts() equivalent (print + newline):
int n = (ch >= 'a' && ch <= 'z') [Link](line);
Input: c ? (ch + 'A' - 'a') : ch;
[Link]((char) n); // BufferedReader alternative:
C } BufferedReader br = new BufferedReader(
} new InputStreamReader([Link]));
String s = [Link]();
UNFORMATTED I/O – MEMORY & DIAGRAM
[Link]() – How character input works in Java:

int ch; (32-bit / 4 bytes)

ch = [Link]();
upper 3 bytes lower byte: 01000001
(ASCII 65 = 'A') [Link]((char)ch);

→ reads 'A', stores ASCII 65

char vs int in Java:

Statement Result / Explanation

char c = 'A'; Stores character 'A' (UTF-16, 16-bit)

int i = 'A'; Stores 65 (ASCII value as int)

[Link](c); Prints: A

[Link](i); Prints: 65

[Link]((char)i); Prints: A (explicit cast back to char)

Complete I/O Quick Reference (C → Java):

C Function Java Equivalent

printf("%d", x) [Link]("%d", x) or [Link](x)

scanf("%d", &x) x = [Link]()

scanf("%f", &x) x = [Link]() or [Link]()

scanf("%s", str) str = [Link]() or [Link]()

gets(str) str = [Link]()

You might also like