Table of Contents
In this Java tutorial, we will review some of the basics of building a Java program such as class Main and public static void main. This Java tutorial will cover three Java program exercises as listed below:
- Exercise 1: Math Basics
- Exercise 2: Math Input Calculator
Exercise 1: Math Basics
In this first exercise, we will write a Java program to print the values of addition, subtraction, multiplication, division and modulus.
Input:
public class Main { public static void main(String[] args) { System.out.println("Addition 5 + 4"); System.out.println(5 + 4); System.out.println("\nSubtraction 9 - 7"); System.out.println(9 - 7); System.out.println("\nMultiplication 4 * 10"); System.out.println(4 * 10); System.out.println("\nDivision 8 / 4"); System.out.println(8 / 4); System.out.println("\nModulus 8 % 4"); System.out.println(8 % 4); } }
Output:
Addition 5 + 4 9 Subtraction 9 - 7 2 Multiplication 4 * 10 40 Division 8 / 4 2 Modulus 8 % 4 0
Exercise 2: Math Input Calculator
In this second exercise, we will write a Java program to print the values of addition, subtraction, multiplication, division and modulus with the users input of the first and second numbers into the Java program.
Input:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner (System.in); System.out.print("Input the first number: "); int a = input.nextInt(); System.out.print("Input the second number: "); int b = input.nextInt(); int add = (a + b); int sub = (a - b); int mul = (a * b); int div = (a / b); int mod = (a % b); System.out.println(); System.out.println("Addition: " + add); System.out.println("\nSubtraction: " + sub); System.out.println("\nMultiplication: " + mul); System.out.println("\nDivision: " + div); System.out.println("\nModulus: " + mod); } }
Output:
Input the first number: 5 Input the second number: 6 Addition: 11 Subtraction: -1 Multiplication: 30 Division: 0 Modulus: 5
I hope this Java tutorial helped to provide the basic knowledge of building a calculator in Java.