Menu
Coddy logo textTech

Formatting Output

Part of the Fundamentals section of Coddy's Java journey — lesson 34 of 73.

As of now, we learned how to print simple strings, but sometimes we need to insert variable values into the string.

For example:

int age = 10;
System.out.println("His age is: age");

This will print "His age is: age" instead of "His age is: 10"

To make it work, we will use formatted printing printf:

int age = 30;
String name = "Alice";
double balance = 1500.75;

System.out.printf("Name: %s, Age: %d, Balance: %.2f\n", name, age, balance);
  • %s is a placeholder for strings.
  • %d is a placeholder for integers.
  • %f is a placeholder for floating-point numbers.
  • %.2f formats the floating-point number to two decimal places.
  • \n is an escape sequence that moves the output to a new line.

Another way to combine strings with variables is with the plus + operator:

System.out.print("Name: " + name + " Age: " +  age + " Balance: " + balance);
challenge icon

Challenge

Beginner

You are given a code that stores a random string as input to a variable named rnd.

Print to the console "The input is: " and the random string that is inside the variable rnd.

Check the test cases for examples!

Cheat sheet

To insert variable values into strings, use printf with placeholders:

int age = 30;
String name = "Alice";
double balance = 1500.75;

System.out.printf("Name: %s, Age: %d, Balance: %.2f\n", name, age, balance);

Placeholders:

  • %s - strings
  • %d - integers
  • %f - floating-point numbers
  • %.2f - floating-point with 2 decimal places
  • \n - newline character (moves output to the next line)

Alternative: concatenate with + operator:

System.out.print("Name: " + name + " Age: " + age + " Balance: " + balance);

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String rnd = scanner.nextLine();
        
        // Write your code below
        
        scanner.close();
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals