Java 03: Input and Output

Standard Streams are a feature of many operating systems. By default, they read input from the keyboard and write output to the display. They also support I/O on files and between programs, but that feature is controlled by the command line interpreter, not the program.

The Java platform supports three Standard Streams: Standard Input, accessed through System.in; Standard Output, accessed through System.out;

Input referring to data that comes into Java program from console where user uses keyboard to key in input text.

Console

Command Prompt is a command line interpreter application available in most Windows operating systems. It's used to execute entered commands. Most of those commands automate tasks via scripts and batch files, perform advanced administrative functions, and troubleshoot or solve certain kinds of Windows issues.

Console Output referring to data that goes out from Java program to the console to be displayed.

Unlike the Graphical User interface console applications interaction with users are text based.

Console input

To perform input operation, java uses System.in interface a standard input stream for java. This interface is wrapped by other class to handle the input stream. Using the Scanner class from the System.util package is one of the preferred ways by many.

Scanner scanner = new Scanner (System.in);

This class provides methods to read the input from the console. For example following code uses nextLine() method to read a string from the console and pass it to input string variable.

String input = scanner.nextLine();

Scanner class provides methods to automatically convert the string input to desired data type as shown below.

nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

Console Output

Uses System.out interface from the System.util package. This does not require wrapping class.

it uses two methods print () and println() to output string to the console window. Both takes a string as its argument and display the string.

Using print()

System.out.print("Have a nice day");

The print () method don’t have termination character at the end of string after display. Need to use “\n” the terminate line.

using println()

System.out.println("Please welcome");

The println() method automatically add the “\n” after display the string.

Both these methods also take numbers are argument and automatically converts them to string before display.

A post by Cuber

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net