Calculate with expressions and strings
Use arithmetic operators and combine values to build output.
- Evaluate arithmetic and distinguish numeric addition from string concatenation.
Java supports arithmetic operators such as +, -, *, /, and % (remainder). When both operands are integers, division truncates the fractional part. The + operator adds numbers, and when a String is involved it can concatenate text. Parentheses make evaluation order clear.
1int total = 17;
2int people = 5;
3System.out.println(total / people);
4System.out.println("Left: " + (total % people));3 Left: 2
Use a double when a calculation needs fractional values, or cast an operand before division. String concatenation is convenient for small messages; formatted output such as printf can control how numbers are displayed.
Key takeaways
Evaluate arithmetic and distinguish numeric addition from string concatenation.
Java checks types as it compiles your source.
Use compiler messages as clues about what needs fixing.
Lesson quiz
4 questions · pass with 3 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Java
Write Java in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.
Convert Celsius to Fahrenheit
Read a Celsius temperature as a double and print Fahrenheit using F = C * 9 / 5 + 32. Keep the calculation in floating point.
- Water freezes
- Room temperature
Java is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…