Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn String Formatting Operations in Java | Strings
Introduction to Java

String Formatting Operations in Java

Swipe to show menu

In real applications, text is constantly shown to users — order confirmations, receipts, notifications, status updates. Raw text is often not enough: it needs structure, readability, and dynamic values that change every time the program runs. That's where string formatting operations come in.

New Line Character \n

If you need to split a single string across multiple lines without using separate println calls, use the \n escape character. It tells Java to move to the next line at that point — like pressing Enter inside a string.

Main.java

Main.java

12345678910
package com.example; public class Main { public static void main(String[] args) { String message = "Welcome to our Coffee Shop\nYour order is being prepared\nThank you for visiting"; System.out.println(message); } }

Instead of printing one long line, Java splits the output at each \n and prints a structured message across three separate lines.

String.format()

If you need to build dynamic messages by inserting values into a fixed template, use String.format(). Instead of manually joining strings with +, you define a template with placeholders and pass the values separately.

Main.java

Main.java

12345678910111213141516171819
package com.example; public class Main { public static void main(String[] args) { String customerName = "Anna"; int orderNumber = 42; double price = 4.99; String message = String.format( "Customer: %s | Order: %d | Price: %.2f", customerName, orderNumber, price ); System.out.println(message); } }

String.format() takes the template string and fills each placeholder with the corresponding value in order — customerName goes into %s, orderNumber into %d, and price into %.2f. The result is a clean, structured line: Customer: Anna | Order: 42 | Price: 4.99.

Format Specifiers

Inside String.format(), placeholders always start with % and define what type of value goes there:

  • %s — text (String);
  • %d — whole numbers (int);
  • %f — decimal numbers (double / float);
  • %.2f — decimal number with exactly 2 digits after the decimal point.
question mark

What does \n do inside a String in Java?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 4. Chapter 3
some-alt