...

/

Arithmetic Operators and Data Types

Arithmetic Operators and Data Types

Learn about the arithmetic operators and data types in Java.

Back to our project

So far, we’ve covered good ground in learning how to code for some of the project requirements. Let’s take a look at our client’s requirements once again.

Project requirements that require printing on the screen
Project requirements that require printing on the screen

According to requirements 4 and 6, our app should be able to:

  • Perform calculations of addition, subtraction, multiplication, and division.

  • Compute the actual answer to each question.

So, let’s dive right in!

Adding two numbers

This should be easy: input two numbers and assign them to num1 and num2, then print num1 + num2. Run the program below and see if we’re getting the expected outputInput 8 and 2. What should be the expected output of 8 + 2?. Let’s enter “8” as the first number and “2” as the second one. Run the program below and see if we’re getting the expected output.

import java.util.Scanner;

public class MyJavaApp {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        //Taking two numbers as input and storing inside two variables respectively
        System.out.print("First number: ");
        String num1 = scan.nextLine();
        System.out.print("Second number: ");
        String num2 = scan.nextLine();
        System.out.println("The answer to " + num1 + " + " + num2 + " is " + num1 + num2);
        
 }
}
Program to add two numbers

But wait a minute! We get the output “82” instead of “10.” Why do you think that is? ...