知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

    • 扩展

      • Theory:Units of information
      • Theory:IDE
      • Theory:IDEA
      • Theory:Build tools
      • Theory:Operating systems
      • Theory:Gradle basics
      • Theory:Basic project with Gradle
      • Theory:Building apps using Gradle
      • Theory:Dependency management
      • Theory:Formatted output
        • Introduction
        • Introducing the printf() method
        • Different use cases of printf()
        • The String.format() Method
        • Summary
        • Conclusion
      • Theory:Libraries
      • Theory:Frameworks
      • Theory:Modules
      • Theory:Introduction to software architecture
      • Theory:Class Diagrams
      • Theory:Text blocks
      • Theory:YAML
      • Theory:XML
      • Theory:JSON
    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • 扩展
Jim
2022-07-09
目录

Theory:Formatted output

# Introduction

You are already familiar with the System.out.print() and System.out.println() methods to print output to the console. But when you need complex formatting of output, these two methods are not really helpful. There are two methods that you can use in such cases, namely, System.out.printf() and String.format(). Let's discuss them in detail and focus on string and number formatting.

# Introducing the printf() method

The printf() method usually has two parts. First, you give the string you want to format as the first attribute. This string itself includes rules to format it via format specifiers. Some examples of format specifiers are %d, %s, etc. In the second part, you give the argument list that Java can use to format the string according to the format-specifiers.

See the following example to understand the different parts of the printf() function.

System.out.printf("My Name is %s. I was born in %d", "Mike", 1998);
1
  • The first part is "My Name is %s. I was born in %d", where %s and %d are the format specifiers.
  • The second part is the argument list: "Mike", 1998 .

# Different use cases of printf()

It's time to know the different use cases of format-specifiers. It's quite easy to understand it with code samples. Let's try now.

You can display an integer with the %d format specifier.

public static void main(String[] args){
    System.out.printf("Display a Number %d", 15000);
}
1
2
3

Java will replace %d with 15000. The output of the above code is Display a Number 15000.

If you want several integers to be displayed in the output, use several %d specifiers.

public static void main(String[] args){
    System.out.printf("The sum of %d and %d is %d", 15, 40, 55);
}
1
2
3

Java will put each argument in place of %d, starting from left. The output of the above code is The sum of 15 and 40 is 55.

If you want to display a floating-point value, use the %f specifier.

public static void main(String[] args){
    System.out.printf("Display a Number %f", 15.23);
}
1
2
3

Similar to the above cases, Java will put 15.23 in place of %f. The above code will produce the following output. Display a Number 15.230000 Although it's technically correct, it looks ugly. You don't want so many trailing zeros. You can set precision with the printf() method.

public static void main(String[] args){
    System.out.printf("Display a Number %.2f", 15.23);
}
.2f` decides that the number of digits that should appear after the **decimal** place is two. The code given above will output `Display a Number 15.23
1
2
3
4

Similarly, you can display Characters and Strings with the printf() method. Take a look at the following code. If you want to print a character, use %c, and if you want to print a String, use %s.

public static void main(String[] args){
    char abbr = 'H';
    String element = "Hydrogen";
    System.out.printf("%c stands for %s", abbr, element);
}
1
2
3
4
5

When this code runs, the value of the abbr variable will replace %c and the value of the element variable will replace %s. The output of the above code is H stands for Hydrogen. That's all about the printf() method. Let's move on to learn about the String.format() method.

# The String.format() Method

The format() method in the String class works very much like the printf() method. The main difference here is that you return a string instead of printing it. Let's see several examples.

The following code formats an integer using it.

public static void main(String[] args){
    int age = 22;
    String str = String.format("My age is %d", age);
    System.out.println(str);
}
1
2
3
4
5

When you execute this code, Java will create a String called str by concatenating My age is with the value of the age variable. Then it will print the value of str. The output is:

My age is 22
1

Similarly, you can format other data types as well. See the following code.

public static void main(String[] args){
    int age = 22;
    char initial = 'M';
    String surname = "Anderson";
    double height = 1.72;

    String details = String.format(
            "My name is %c. %s.%nMy age is %d.%nMy height is %.2f.",
            initial, surname, age, height);
    System.out.println(details);
}
1
2
3
4
5
6
7
8
9
10
11

You can see that we have used four data types in this example. Java will replace %c, %s, %d, %f with initial, surname, age, and height respectively. %n is the newline character that breaks the line every time it is used. The output of our code is:

My name is M. Anderson.
My age is 22.
My height is 1.72.
1
2
3

The String class also has a newer and slightly simpler method formatted(Object... args) that you can use instead of the static String.format method. Both of them have the same method body, so they are completely interchangeable. Here's how it looks in the program:

public static void main(String[] args) {
    int age = 22;
    char initial = 'M';
    String surname = "Anderson";
    double height = 1.72;

    String details = "My name is %c. %s.%nMy age is %d.%nMy height is %.2f."
            .formatted(initial, surname, age, height);

    System.out.println(details);
}
1
2
3
4
5
6
7
8
9
10
11

The result is exactly the same as with the String.format method:

My name is M. Anderson.
My age is 22.
My height is 1.72.
1
2
3

Keep in mind that formatted is an instance method whereas the String.format method is a static one. You don't need to focus on this difference right now; you will learn about instance and static methods in the future.

# Summary

Let's summarize what we've learned in this topic.

Format-Specifier datatype Format printing Formatting a string
%d int, short, byte, long System.out.printf("Display an Integer %d",15000); String.format("Display an Integer %d",15000)
%c char System.out.printf("Display a Character %c",'c'); String.format("Display a Character %c",'c')
%f double, float System.out.printf("Display a Floating-point Number %f",123.45); String.format("Display a Floating-point Number %f",123.45)
%s String System.out.printf("Display a String %s","String"); String.format("Display a String %s","String")

# Conclusion

When you are writing complex applications, combining strings and variables with a + sign is not recommended. The printf() and format() methods are specifically created for that. Both these methods work exactly the same way except that the printf()method prints the output, while the format() method returns a String. In this article, you have learned most of the uses of both functions. Enjoy it.

编辑 (opens new window)
#Java#String#Code style
上次更新: 2022/09/26, 16:55:15
Theory:Dependency management
Theory:Libraries

← Theory:Dependency management Theory:Libraries→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式