Beginner level · Module 1: Java Setup and First Programs · Lesson 3 of 3
Variables, Types and Formatted Output
Store numbers, text and true/false values in typed variables, calculate with operators and print readable results.
In this lesson you will
- Choose suitable types: int, long, double, boolean, char and String
- Use arithmetic operators and printf to format results
Key concepts
static typingint vs doubleinteger divisionprintf
The lesson
Java is statically typed: every variable has a type fixed at compile time. int holds whole numbers, long holds larger whole numbers, double holds decimals, boolean holds true or false, char holds one character, and String holds text. The compiler rejects code that puts the wrong kind of value into a variable.
Division between two ints drops the remainder: 7 / 2 is 3. If either value is a double, the result is a double: 7 / 2.0 is 3.5. The remainder operator % gives what is left over, so 7 % 2 is 1. Mistakes with integer division are one of the most common beginner bugs.
System.out.printf formats output: %d for whole numbers, %.2f for a decimal with two places, %s for text and %n for a new line. For example printf("%-10s %,8d SSP%n", "Rice", 14000) prints a left-aligned name and a right-aligned number with a thousands separator.
Step by step
- Declare an int quantity, a double unitPrice and a String item.
- Calculate the total and store it in a double.
- Print the result with printf using %s, %d and %.2f.
- Change the values and run again to check the calculation.
Practice activity
Write a fuel-cost calculator: distance in km, litres per 100 km and price per litre in SSP, printing the litres needed and total cost with two decimals.
Expected result: For 250 km at 8 litres per 100 km and 1,200 SSP per litre, the program prints 20.00 litres and 24,000.00 SSP.
Check your understanding
-
What is 9 / 4 in Java when both are ints?
Show answer
2 — integer division drops the remainder.
-
Which format specifier prints a decimal with two places?
Show answer
%.2f
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.