AI Hints
Home›Java Tutorial›char and boolean, Type Casting, Practice: A Simple Calculator
Java · Lesson 18 of 120

Practice: A Simple Calculator

Put module two together.

⏱ 2 min read▶ Video at 23:28🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Let's put module two together. Two numbers, and all five operators, printed neatly.

  • Two numbers
  • Five operators
  • Neat output

A simple calculator

Your turn. Pause the video, and try this. Store twenty three, and four, in two int variables. Then print each operation, with the full sum written out. For division, cast to double, so we keep the decimals. Here is one solution. Each line joins the numbers, the symbol, and the answer, in brackets. Division gives five point seven five, and the remainder is three.

✍️ Exercise: A simple calculator

Store 23 and 4. Print +, -, *, / (with decimals) and % as full sums, like "23 + 4 = 27".

Show hint

(double) a / b keeps the decimals

Show solution
Main.javajava
public class Main {
    public static void main(String[] args) {
        int a = 23;
        int b = 4;
        System.out.println(a + " + " + b + " = " + (a + b));
        System.out.println(a + " - " + b + " = " + (a - b));
        System.out.println(a + " * " + b + " = " + (a * b));
        System.out.println(a + " / " + b + " = " + (double) a / b);
        System.out.println(a + " % " + b + " = " + (a % b));
    }
}
Output
23 + 4 = 27
23 - 4 = 19
23 * 4 = 92
23 / 4 = 5.75
23 % 4 = 3

What module two taught

Variables have a type, a name, and a value. Int and long hold whole numbers, and double holds decimals. Char holds one character, and boolean, true or false. Int divided by int drops decimals, and percent gives the remainder. And casting converts between types.

keyvalue
Variablestype name = value;
Numbersint, long, double
Otherschar, boolean
Tricks/, %, (double) casts

Summary

You can now store values, and do maths with them. That's the end of module two. Next module, strings, and reading input.

Key takeaways
  • Types and variables
  • Maths and remainders
  • Casting
Next up: Strings — text in Java