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);%sis a placeholder for strings.%dis a placeholder for integers.%fis a placeholder for floating-point numbers.%.2fformats the floating-point number to two decimal places.\nis 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
BeginnerYou 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();
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else