Java Developers Toolbox - Formatting Strings
Java Developer's Toolbox
This training course walks you through many of the commonly used Java programming techniques such as autoboxing and unboxing. We’ll also cover several of the SDK base libraries and utility classes for working with Java primitives, Strings and DateTimes, etc.
- Understand what wrapper classes are and when to use them
- Be able to explain autoboxing and unboxing
- Be able to work with and define enumerations
- Make use of static imports
- Explain the core DateTime classes
- Modify and format DateTime values
- Work with time zone information
- Format Strings using the formatter syntax
- And be able to confidently use System.out and System.format to print out strings
- A basic understanding of software development
- A basic understanding of the software development life cycle
- Software Engineers interested in learning Java to develop applications
- Software Architects interested in learning Java to design applications
- Anyone interested in basic Java application development and associated tooling
- Anyone interested in understanding the basics of the Java SDK
Okay, welcome back. In this lecture we'll take you through various techniques for formatting strings within Java. We'll cover items such as: formatting a String using the formatter syntax. Applying text formatting using the Formatter class. And using String.format and System.out.printf. Inspired by C's String formatting options, Java 5 introduced printf functionality allowing for the creation of formatted text. Often we need to create text which consists of templated text combined with variable values. The printf functionality allows us to do just that. The method takes a format-string which consists of a combination of literal text and format specifiers. Each format-specifier x is a placeholder for the live value. Defining not only the location of the variable but also how it should be formatted when inserted into the final text. The format-specifiers that are to be placed in the template String consist of a percentage sign followed by at least a type identifier e.g. Format as String decimal or date type. Additional arguments allow for the definition of formatting or layout information. For example padding left or right, minimum number of characters used or decimal digits to be displayed. The types that can be formatted are divided into several categories. The formatting types that can be applied depend on the category of the value to be formatted. Valid conversions depend on type. General can be applied to any type. Character, any basic representing Unicode character. Integral, any integral type, byte, short, int, long. Floating point, any floating point type, float, double, BigDecimal. And date time. Types capable of encoding date or time, long, calendar, date et cetera. Depending on the category of the value to be formatted, one or more format-specifier letters can be selected to format the value. Keep in mind that all data is formatted according to the pre-defined locale. Unless a specific locale is defined, the system's default locale is being used. For example when formatting floating point values, the decimal separated differs depending on the locale being used. While the internationalized names of months and days of week might be used when formatting a value in the date category. Some type conversions are defined using both in lowercase and uppercase letter.
When the uppercase letter is used the result will also be generated in uppercase. The Formatter class, x is the interpreter for all printf-style strings. It allows for the template string to be interpreted and the format-specifiers to be replaced by their actual values. The format method of this class was implemented as a fluent API. Returning a reference to the Formatter instance allowing for multiple individual format operations to be defined resulting in a single string. When an instance of this class is created using the default constructor, the formatted text is appended to an internal Appendable instance string builder. An overloaded constructor allows for the definition of the locale to be used for the formatting. Instead of using the default Appendable instance to hold the result of the format operation. Alternatives can be defined when creating an instance of the Formatter class. Not only can an external Appendable for example string builder be defined, it is also possible to have the instance write the result to a file, OutputStream or PrintStream. The printf and format methods have been added to the PrintStream class. Since System.out references an instance of this class it is now possible to use the printf functionality when writing text to standard out. The behavior of the printf and format methods is identical. In order to stay in sync with the other APIs both options have been provided. Keep in mind that the printf method does not add a line break unlike the print line method. In order to add a line break, a percentage sign in character sequence should be added to the text template. Percentage in adds a platform independent line break. A static format method has been added to the String class. Invoking this method results in a new String object containing the output of the format operation. The code example shown here shows some examples of how a String might be formatted. While percentage s formats the text as is, percentage uppercase S formats the text in uppercase. When the variable to be formatted as a String is a non String object the dot two String method of this object is null. When the object reference is a null pointer, the text null will be inserted into the String. The minimum width of the string can also be defined as well as the padding that should be applied left or right. When the provided values is shorter than the minimum width specified. By using the precision notation, starting with a dot followed by a numeric value the maximum length of the String can be defined. When the length of the supplied value exceeds the maximum length, the value will be truncated. Just like with string types, numeric types can also be defined using a minimum width. Adding a minus sign to indicate padding on the right instead of the left. When the length is prefixed with a zero, the value is padded with zeros on the left when the size of the provided value is less than the minimum length. For floating point values, the number of decimal digits can be defined by specifying the precision. Starting with a dot followed by a numeric value. When a precision is defined for an integer value, a runtime exception will be thrown. When the number of decimal digits provided exceeds the maximum number of digits to be displayed, the value will be rounded. By default, when defining the values for each format-specifier in the template, you will have to provide the values in the same order as the order in which the format-specifiers are defined within the template. When the order of the values differs, or a single value should be added to the String multiple times, the format-specifier can be defined using an argument index. The argument index should be added directly after the percentage sign. And should be followed by a dollar sign. In order to work with a date or time, it is not sufficient to only define a single letter. You must also define how the date or time should be formatted. The lowercase or uppercase letter t should be used to start the definition of a date/time format-specifier. The letter that follows this letter t defines how or what should be generated in the result. In most cases, you want to output multiple fields of a single date/time object. In the example shown here, the month and the year are outputted so you would have to use an argument index notation to reference the same value multiple times. Formatting suffixes can be applied to format time fields. Several letters have been defined to format the various fields of an object which represents time. The formatting language is an extremely flexible API as can be seen by the specification. Just like when formatting time based values, individual letters have been defined to specify various properties of a date based value. For the formatting of date/time based values, several special conversion characters have been defined for the most commonly used date/time conversions. Okay, consider the following questions to test yourself on the content we've just reviewed. The answers to the above questions are: one, it takes a String or template and a variable argument list of object references returning a String as the result. Okay, there completes this lecture, go ahead and close it and we'll see you shortly in the next one.
Jeremy is a Content Lead Architect and DevOps SME here at Cloud Academy where he specializes in developing DevOps technical training documentation.
He has a strong background in software engineering, and has been coding with various languages, frameworks, and systems for the past 25+ years. In recent times, Jeremy has been focused on DevOps, Cloud (AWS, GCP, Azure), Security, Kubernetes, and Machine Learning.
Jeremy holds professional certifications for AWS, GCP, Terraform, Kubernetes (CKA, CKAD, CKS).