Now that we know how to declare and initialize variables in Java, we can do some mathematics with those variables.
1
public
class
MathOperations
{
2
public
static
void
main
(
String
[]
args
)
{
3
int
a
,
b
,
c
,
d
,
e
,
f
,
g
;
4
double
x
,
y
,
z
;
5
String
one
,
two
,
both
;
6
7
a
=
10
;
8
b
=
27
;
9
System
.
out
.
println
(
"a is "
+
a
+
", b is "
+
b
);
10
11
c
=
a
+
b
;
12
System
.
out
.
println
(
"a+b is "
+
c
);
13
d
=
a
-
b
;
14
System
.
out
.
println
(
"a-b is "
+
d
);
15
e
=
a
+
b
*
3
;
16
System
.
out
.
println
(
"a+b*3 is "
+
e
);
17
f
=
b
/
2
;
18
System
.
out
.
println
(
"b/2 is "
+
f
);
19
g
=
b
%
10
;
20
System
.
out
.
println
(
"b%10 is "
+
g
);
21
22
x
=
1.1
;
23
System
.
out
.
println
(
"\nx is "
+
x
);
24
y
=
x
*
x
;
25
System
.
out
.
println
(
"x*x is "
+
y
);
26
z
=
b
/
2
;
27
System
.
out
.
println
(
"b/2 is "
+
z
);
28
System
.
out
.
println
();
29
30
one
=
"dog"
;
31
two
=
"house"
;
32
both
=
one
+
two
;
33
System
.
out
.
println
(
both
);
34
}
35
}
The plus sign (+
) will add two integers or two doubles together, or one
integer and one floating-point value (in either order). With two Strings
(like on line 32) it will concatenate5 the two Strings together.
The minus sign (-
) will subtract one number from another. Just like
addition, it works with two integers, two floating-point values, or one
integer and one double (in either order).
An asterisk (*
) is used to represent multiplication. You can also see
on line 15 that Java knows about the correct order of operations. b
is multiplied by 3 giving 81
and then a is added.
A slash (/
) is used for division. Notice that when an integer
is divided by another integer (like on line 17) the result is also
an integer and not floating-point.
The percent sign (%
) is used to mean ‘modulus’, which is essentially
the remainder left over after dividing. On line 19, b is divided by 10
and the remainder (7
) is stored into the variable g.
Modular arithmetic is a fairly simple mathematical operation that just isn’t often taught in public school or even introductory university math curriculum. Wikipedia’s example is good enough: we do modular arithmetic every time we add times on a typical 12-hour clock. If it is 7 o’clock now, what time will it be in eight hours? Well, once we hit 12:00 we “wrap around”, so it will be 3 o’clock. (8+7 = 15, 15-12 = 3)
Put another way, 15 divided by 12 is 1 with a remainder of 3.
Modular arithmetic is used more than you would think in programming, but I won’t be using it too much in the book.
Footnotes:
“Learn Java the Hard Way” is ©2013–2016 Graham Mitchell