Skip to content

Operations

  • Lesson
  • 3 min read
  • 6 of 8 in this chapter

Let's talk operations

Ok, operations. What are they? Well, if you know how to add, subtract, multiply, and divide, you know exactly what they are.

We can use operations in a variety of ways with our variables.

Addition

We can use addition in a variety of ways. To add variables or values together, just use +. Let's see some examples.

Java
int x = 1;
int y = 3;
int solution1 = x + y;
         
double a = 3.5;
double b = 4.1;
double solution2 = a + b;
         
String first = "Rodrick";
String last = "Heffley";
String name = first + " " + last;

System.out.println(solution1);
System.out.println(solution2);
System.out.println(name);

And the output:

Text
4
7.6
Rodrick Heffley

So we can add ints, doubles, and Strings. Try the other primitive types and see what happens! Not all types can be added together.

What you can also see above is that we made a new variable set to the sum of two others. For example, changing the value of x changes the value of solution1.

Subtraction

To subtract variables or values, just use -. Let's see some examples.

Java
int x = 1;
int y = 3;
int solution1 = y - x;
         
double a = 3.5;
double b = 4.1;
double solution2 = a - b;

System.out.println(solution1);
System.out.println(solution2);

And the output:

Text
2
-0.5999999999999996

Notice how we weren't able to subtract Strings, hence the exclusion above.

You might also see the -0.5999999999999996 and be very confused. We'll talk about why this happens in the next lesson. (It is pretty close to -0.6 though)

Multiplication

To multiply variables or values, just use *. Let's see some examples.

Java
int x = 1;
int y = 3;
int solution1 = x * y;
         
double a = 3.5;
double b = 4.1;
double solution2 = a * b;

System.out.println(solution1);
System.out.println(solution2);

And the output:

Text
3
14.349999999999998

Division

To divide variables or values, just use /. Let's see some examples.

Java
int x = 1;
int y = 3;
int solution1 = y / x;
         
double a = 3.5;
double b = 4.1;
double solution2 = a / b;

System.out.println(solution1);
System.out.println(solution2);

And the output:

Text
3
0.853658536585366

Modulo

What is Modulo?? Modulo is an operator to get the remainder of a division operator. To use modulo, just use %. Here are some examples:

Java
int x = 5;
int y = 2;

System.out.println(x % y);

Here's the output:

Text
1

5 divided by 2 is 2 with a remainder of 1. That's what we get from modulo.

In the next lesson, we will learn about casting, rounding, and more ways to set variables.