Arithmetic Operators
Arithmetic Operators
System.out.print(7 + 3);
int a = 7;
int b = 3;
System.out.print(a + b);
challenge
int a = 0;
a = a + 1;
System.out.print(a);
a = a + 1
The variable a appears twice on the same line of code. But each
instance of a refers to something different.
How to Read a = a + 1
++ +=
challenge
String Concatenation
String concatenation is the act of combining two strings together.
This is done with the + operator.
challenge
challenge
Change b to -3 ?
Change c to c = a - -b ?
Change b to 3.0 ?
-- -=
int a = 10;
a--;
System.out.println(a);
double a = 25;
double b = 4;
System.out.println(a / b);
challenge
Change b to 0 ?
Change b to 0.5 ?
Change the code to
double a = 25;
double b = 4;
a /= b;
System.out.println(a);
Hint
/= works similar to += and -=
.guides/img/intDivision
int a = 5;
int b = 2;
System.out.println(a / b);
Type casting (or type conversion) is when you change the data
type of a variable.
challenge
More Info
If either or both numbers in Java division are a double , then
double division will occur. In the last example, numerator and
denominator are both int when the division takes place - then
the integer division result is converted to a double.
int a = 5;
String b = "3";
System.out.println(a + Integer.parseInt(b));
challenge
Modulo
int modulo = 5 % 2;
System.out.println(modulo);
challenge
Change modulo to 5 % -2 ?
Change modulo to 5 % 0 ?
Change modulo to 5 % 2.0 ?
Java uses the * operator for multiplication.
int a = 5;
int b = 10;
System.out.println(a * b);
challenge
Change b to 0.1 ?
Change b to -3 ?
Hint
*= works similar to += and -=
Java uses the PEMDAS method for determining order of
operations.
PEMDAS
int a = 2;
int b = 3;
int c = 4;
double result = 3 * a - 2 / (b + 5) + c;
System.out.println(result);
Explanation
The first step is to compute b + 5 (which is 8 ) because it is
surrounded by parentheses.
Next, do the multiplication and division going from left to
right. 3 * a is 6 .
2 divided by 8 is 0 (remember, the / operator returns an
int when you use two int s so 0.25 becomes 0 ).
5 + 7 - 10 * 3 /0.5
Solution
-48.0
(5 * 8) - 7 % 2 - (-1 * 18)
Solution
57.0
9 / 3 + (100 % 0.5) - 3
Solution
0.0