Scanning and Formatting

Programming I/O often involves translating to and from the neatly formatted data humans like to work with. To assist you with these chores, the Java platform provides two APIs. The scanner API breaks input into individual tokens associated with bits of data. The formatting API assembles data into nicely formatted, human-readable form.


Objects of type Scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type.

By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators.Consider the following example

import java.util.Scanner;

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

		Scanner s = null;

		try {
			s = new Scanner(new BufferedReader(new FileReader("abc.txt")));

			while (s.hasNext()) {
		} finally {
			if (s != null) {


Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a standard set of write methods for simple byte and character output. In addition, both PrintStream and PrintWriter implement the same set of methods for converting internal data into formatted output. Two levels of formatting are provided:

-print and println format individual values in a standard way.
-format formats almost any number of values based on a format string, with many options for precise formatting.

Consider the following example.

public class FormattingExample {
	public static void main(String[] args) {

		// print
		System.out.print("this will printed without no line");

		// printline
		System.out.println("this will printed with new line");

		// The format Method
		int i = 2;
		double r = Math.sqrt(i);

		System.out.format("The square root of %d is %f.%n", i, r);