- Formatting
- The print and println Methods
- The format Method
- Class PrintStream
- Field Summary
- Fields declared in class java.io.FilterOutputStream
- Constructor Summary
- Print a String in Java
- Using the print() Method to Print a String in Java
- Using Scanner Input and println Method to Print a String in Java
- Using the printf() Method to Print a String in Java
- Related Article — Java String
Formatting
Stream objects that implement formatting are instances of either PrintWriter , a character stream class, or PrintStream , a byte stream class.
Note: The only PrintStream objects you are likely to need are System.out and System.err . (See I/O from the Command Line for more on these objects.) When you need to create a formatted output stream, instantiate PrintWriter , not PrintStream .
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.
The print and println Methods
Invoking print or println outputs a single value after converting the value using the appropriate toString method. We can see this in the Root example:
Here is the output of Root :
The square root of 2 is 1.4142135623730951. The square root of 5 is 2.23606797749979.
The i and r variables are formatted twice: the first time using code in an overload of print , the second time by conversion code automatically generated by the Java compiler, which also utilizes toString . You can format any value this way, but you don’t have much control over the results.
The format Method
The format method formats multiple arguments based on a format string. The format string consists of static text embedded with format specifiers; except for the format specifiers, the format string is output unchanged.
Format strings support many features. In this tutorial, we’ll just cover some basics. For a complete description, see format string syntax in the API specification.
The Root2 example formats two values with a single format invocation:
The square root of 2 is 1.414214.
Like the three used in this example, all format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the kind of formatted output being generated. The three conversions used here are:
- d formats an integer value as a decimal value.
- f formats a floating point value as a decimal value.
- n outputs a platform-specific line terminator.
Here are some other conversions:
- x formats an integer as a hexadecimal value.
- s formats any value as a string.
- tB formats an integer as a locale-specific month name.
There are many other conversions.
Except for %% and %n , all format specifiers must match an argument. If they don’t, an exception is thrown.
In the Java programming language, the \n escape always generates the linefeed character ( \u000A ). Don’t use \n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n .
In addition to the conversion, a format specifier can contain several additional elements that further customize the formatted output. Here’s an example, Format , that uses every possible kind of element.
3.141593, +00000003.1415926536
The additional elements are all optional. The following figure shows how the longer specifier breaks down into elements.
Elements of a Format Specifier.
The elements must appear in the order shown. Working from the right, the optional elements are:
- Precision. For floating point values, this is the mathematical precision of the formatted value. For s and other general conversions, this is the maximum width of the formatted value; the value is right-truncated if necessary.
- Width. The minimum width of the formatted value; the value is padded if necessary. By default the value is left-padded with blanks.
- Flags specify additional formatting options. In the Format example, the + flag specifies that the number should always be formatted with a sign, and the 0 flag specifies that 0 is the padding character. Other flags include — (pad on the right) and , (format number with locale-specific thousands separators). Note that some flags cannot be used with certain other flags or with certain conversions.
- The Argument Index allows you to explicitly match a designated argument. You can also specify < to match the same argument as the previous specifier. Thus the example could have said: System.out.format("%f, %
Class PrintStream
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException ; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method of the underlying output stream is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ( ‘\n’ ) is written.
All characters printed by a PrintStream are converted into bytes using the given encoding or charset, or the platform’s default character encoding if not specified. The PrintWriter class should be used in situations that require writing characters rather than bytes.
This class always replaces malformed and unmappable character sequences with the charset’s default replacement string. The CharsetEncoder class should be used when more control over the encoding process is required.
Field Summary
Fields declared in class java.io.FilterOutputStream
Constructor Summary
Creates a new print stream, without automatic line flushing, with the specified file name and charset.
Creates a new print stream, without automatic line flushing, with the specified file name and charset.
Print a String in Java
- Using the print() Method to Print a String in Java
- Using Scanner Input and println Method to Print a String in Java
- Using the printf() Method to Print a String in Java
In Java, the string is an object that represents a sequence of characters. Here we will look at various methods to print a string in Java.
Using the print() Method to Print a String in Java
In the code snippet given below, we have a string-type variable, str . To print the value of this variable for the user on the console screen, we will use the print() method.
We pass the text to be printed as a parameter to this method as a String . The cursor stays at the end of the text at the console, and the next print starts from the same line as we can see in the output.
public class StringPrint public static void main(String[] args) String str = "This is a string stored in a variable."; System.out.print(str); System.out.print("Second print statement."); > >
This is a string stored in a variable.Second print statement.
Using Scanner Input and println Method to Print a String in Java
Here, we use the Scanner class to get input from the user.
We create an object of the Scanner class, and we ask the user to enter his name using the print() method. We call the nextLine() method on the input object to get the user’s input string.
The user input is stored in a String type variable. Later, we used the println() method to print the concatenated string and the + operator to concatenate two strings.
Then, the print() and println() methods are used to print the string inside the quotes. But in the println() method, the cursor moves to the beginning of the next line.
At last, we close the scanner input using the close() method.
import java.util.Scanner; public class StringPrint public static void main(String[] args) Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); String name = input.nextLine(); System.out.println("Your name is "+name); input.close(); > >
Enter your name: Joy Your name is Joy
Using the printf() Method to Print a String in Java
The printf() method provides string formatting. We can provide various format specifiers; based on these specifiers, it formats the string and prints it on the console.
Here we have used two format specifiers, %s and %d , where %s is used for string while %d is used for signed decimal integer. We have also used \n , which inserts a new line at a specific point in the text.
public class StringPrint public static void main(String[] args) String str = "The color of this flower is "; int i = 20; System.out.printf("Printing my string : %s\n",str); System.out.printf("Printing int : %d\n",i); > >
Printing my string : The color of this flower is Printing int : 20
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Related Article — Java String
Copyright © 2023. All right reserved