Input and Output
To make our example programs more interesting, we want to accept input and properly format the program output. Of course, modern programs use a GUI for collecting user input. However, programming such an interface requires more tools and techniques than we have at our disposal at this time. Because the first order of business is to become more familiar with the Java programming language, we make do with the humble console for input and output for now.
You saw that it is easy to print output to the “standard output stream” (that is, the console window) just by calling System.out.println. Reading from the “standard input stream” System.in isn’t quite as simple. To read console input, you first construct a Scanner that is attached to System.in:
Now you use the various methods of the Scanner class to read input. For example, the nextLine method reads a line of input.
Here, we use the nextLine method because the input might contain spaces. To read a single word (delimited by whitespace), call
Similarly, the nextDouble method reads the next floating-point number.
The program in Listing below asks for the user’s name and age and then prints a message like
at the beginning of the program. The Scanner class is defined in the java.util package.
Whenever you use a class that is not defined in the basic java.lang package, you need to use an import directive.
NOTE: The Scanner class is not suitable for reading a password from a console since the input is plainly visible to anyone. Java SE 6 introduces a Console class specifically for this purpose. To read a password, use the following code:
For security reasons, the password is returned in an array of characters rather than a string. After you are done processing the password, you should immediately overwrite the array elements with a filler value. (Array processing.
Input processing with a Console object is not as convenient as with a Scanner. You can onlyread a line of input at a time. There are no methods for reading individual words or numbers.
API java.util.Scanner 5.0
API java.lang.system 1.0
API java.io.Console 6
You can print a number x to the console with the statement System.out.print(x). That command will print x with the maximum number of non-zero digits for that type. For example,prints 3333.3333333333335
That is a problem if you want to display, for example, dollars and cents. In early versions of Java, formatting numbers was a bit of a hassle. Fortunately, Java SE 5.0 brought back the venerable printf method from the C library. For example, the call
prints x with a field width of 8 characters and a precision of 2 characters. That is, the printout contains a leading space and the seven characters
You can supply multiple parameters to printf. For example:
Each of the format specifiers that start with a % character is replaced with the corresponding argument. The conversion character that ends a format specifier indicates the type of the value to be formatted: f is a floating-point number, s a string, and d a decimal integer. Table below shows all conversion characters.
Conversions for printf
In addition, you can specify flags that control the appearance of the formatted output.
Table below shows all flags. For example, the comma flag adds group separators. That is,prints 3,333.33
You can use multiple flags, for example, "%,(.2f", to use group separators and enclose negative numbers in parentheses.
Flags for printf
NOTE: You can use the s conversion to format arbitrary objects. If an arbitrary object implements the Formattable interface, the object’s formatTo method is invoked. Otherwise, the toString method is invoked to turn the object into a string.
You can use the static String.format method to create a formatted string without printingit:
Although we do not describe the Date type in detail, we do, in the interest of completeness, briefly discuss the date and time formatting options of the printfmethod. You use a two-letter format, starting with t and ending in one of the letters of Table below. For example,prints the current date and time in the format Mon Feb 09 18:05:19 PST 2004
Date and Time Conversion Characters
As you can see in Table above, some of the formats yield only a part of a given date, for example, just the day or just the month. It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the %, and it must be terminated by a $. For example,prints Due date: February 9, 2004
Alternatively, you can use the <flag. It indicates that the same argument as in the preceding format specification should be used again. That is, the statement
yields the same output as the preceding statement.
CAUTION: Argument index values start with 1, not with 0: %1$...formats the first argument. This avoids confusion with the 0 flag.
You have now seen all features of the printf method. a syntax diagramfor format specifiers.
Format specifier syntax
NOTE: A number of the formatting rules are locale specific. For example, in Germany, the decimal separator is a period, not a comma, and Monday is formatted as Montag. You will see in Volume II how to control the international behavior of your applications.
File Input and Output
To read from a file, construct a Scanner object from a File object, like this:
If the file name contains backslashes, remember to escape each of them with an additional backslash:
Now you can read from the file, using any of the Scanner methods that we already described.
To write to a file, construct a PrintWriter object. In the constructor, simply supply the file name:
If the file does not exist, you can simply use the print, println, and printf commands asyou did when printing to System.out.
CAUTION: You can construct a Scanner with a string parameter, but the scanner interprets the string as data, not a file name. For example, if you call
then the scanner will see ten characters of data: 'm', 'y','f', and so on. That is probably not what was intended in this case.
NOTE: When you specify a relative file name, such as "myfile .txt", "mydirectory /myfile .txt", or "../myfile .txt", the file is located relative to the directory in which the Java virtual machine was started. If you launched your program from a command shell, by executing
then the starting directory is the current directory of the command shell. However, if you use an integrated development environment, the starting directory is controlled by the IDE. You can find the directory location with this call:
If you run into grief with locating files, consider using absolute path names such as
As you just saw, you can access files just as easily as you can use System.in and System.out. There is just one catch: If you construct a Scanner with a file that does not exist or a Print-Writer with a file name that cannot be created, an exception occurs. The Java compiler considers these exceptions to be more serious than a “divide by zero” exception, for example.Later, you will learn various ways for handing exceptions. For now, you should simply tell the compiler that you are aware of the possibility of a “file not found” exception. You do this by tagging the main method with a throws clause, like this:
You have now seen how to read and write files that contain textual data.
NOTE: When you launch a program from a command shell, you can use the redirection syntax of your shell and attach any file to System.in and System.out:
Then, you need not worry about handling the File Not Found Exception.
API java.io.PrintWriter 1.1
API java.io.File 1.0
Core Java Related Interview Questions
|J2EE Interview Questions||Core Java Interview Questions|
|JDBC Interview Questions||JSP Interview Questions|
|Android Interview Questions||JavaServer Faces (JSF) Interview Questions|
|Java collections framework Interview Questions||Java 8 Interview Questions|
|Java Collections Interview Questions||Java Exception Handling Interview Questions|
|Java Concurrency Interview Questions||Java Serialization Interview Questions|
|Java Programmer Interview Questions||Java Inheritance Interview Questions|
|Java IO Interview Questions||Object Oriented Programming in PHP Interview Questions|
Core Java Tutorial
An Introduction To Java
The Java Programming Environment
Fundamental Programming Structures In Java
Objects And Classes
Interfaces And Inner Classes
User Interface Components With Swing
Deploying Applications And Applets
Exceptions, Logging, Assertions, And Debugging
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.