Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Introduction to String.format() | Mastering String.format()
/
Formatting and Parsing in Java

bookIntroduction to String.format()

メニューを表示するにはスワイプしてください

Formatting strings is a fundamental part of producing clear, user-friendly output in Java programs. When you need to display information on the console or in logs, simply joining values together with the plus operator can quickly become messy and hard to read. This is where String.format() comes in. It allows you to build complex strings with embedded variables in a way that is both concise and highly readable. By using String.format(), you gain greater control over how your data is presented, making your output more professional and your code easier to maintain.

Main.java

Main.java

copy
12345678910
package com.example; public class Main { public static void main(String[] args) { String name = "Alice"; int age = 30; String message = String.format("My name is %s and I am %d years old.", name, age); System.out.println(message); } }

In the example above, you see how String.format() is used to insert values into a template string. The placeholders %s and %d are called format specifiers. %s is used for strings, and %d is used for integers. When String.format() is called, it replaces each specifier with the corresponding argument in order. This approach keeps your string-building code neat and makes it easy to see exactly how the output will look.

Main.java

Main.java

copy
123456789101112
package com.example; public class Main { public static void main(String[] args) { String product = "Laptop"; int quantity = 5; double price = 799.99; String summary = String.format("Product: %s | Quantity: %d | Price: $%.2f", product, quantity, price); System.out.println(summary); } }

1. What is the primary benefit of using String.format() over string concatenation in Java?

2. Which format specifier would you use to insert an integer value using String.format()?

3. What will happen if you provide fewer arguments than format specifiers in String.format()?

question mark

What is the primary benefit of using String.format() over string concatenation in Java?

正しい答えを選んでください

question mark

Which format specifier would you use to insert an integer value using String.format()?

正しい答えを選んでください

question mark

What will happen if you provide fewer arguments than format specifiers in String.format()?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  1
some-alt