Java Math Operators and Math Class Tutorial
In this tutorial, I will demonstrate how to perform the mathematic operations via the build-in Math operators and the Java Math class.
Table Of Contents
1. Introduction
Java language has provided a list of operator symbols to perform specific operations on one, two, or three operands and then returning a result. Java operators are generally used to manipulate primitive data types: boolean, byte, char, short, int, long, float and double. The Java operators are classified into eight different categories:
- assignment:
= - arithmetic:
+,-,*,/,%,++, and-- - relational:
==,!=,>,<,>=, and<= - logical:
&&,||, and! - bit-wise:
&,|, and^ - compound assignment:
+=,-=,*=,/=, and%= - conditional:
?: - type comparison:
instanceof
The Java Math class provides advanced mathematical calculations than what the math operators provide, such as square root of a number, etc.
In this example, I will demonstrate how to use these math operators and the java.lang.Math methods to perform the mathematics operations.
2. Technologies Used
The example code in this article was built and run using:
- Java 11
- Maven 3.3.9
- Eclipse Oxygen
- JUnit 4.12
3. Maven Project
3.1 Dependency
Add JUnit to the pom.xml.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jcg.zheng.demo</groupId> <artifactId>java-math-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <release>11</release> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
3.2 Java Object
I will create a POJO class which has only one String data member: name. It will be used to demonstrate the “==” and “!=” operators on an object.
POJO.java
package jcg.zheng.demo.data;
public class POJO {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.3 Java Object Has Equals Method
I will create a POJOHasEquals class which has equals and hashCode methods. It will be used to demonstrate the “==” operator and equals method on an object.
POJOHasEquals.java
package jcg.zheng.demo.data;
public class POJOHasEquals {
private String name;
public POJOHasEquals() {
super();
}
public POJOHasEquals(String name) {
super();
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
POJOHasEquals other = (POJOHasEquals) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public void setName(String name) {
this.name = name;
}
}
4. Arithmetic Operators
Java language provides the following arithmetic operators to operate on the primitive data types: int, byte, short, long, float, double.
+ | returns the sum of two numbers |
- | returns the difference of two numbers |
* | returns the product of two numbers |
/ | returns the quotient when performing the division |
% | returns the remainder of two numbers |
++ | returns the number by adding 1 to it |
-- | returns the number by subtracting 1 from it |
The result’s data type is based on the operand with the higher precision. Here are the rules:
- If either operand is of type
double, the other operand is converted todoubleand the result is also of typedouble. - If either operand is of type
float, the other operand is converted tofloatand the result is also of typefloat. - If either operand is of type
long, the other operand is converted tolongand the result is also of typelong. - If either operand is of type
int, the other operand is converted tointand the result is of typeint. - For all other cases, both operands are converted to
intand the result is of typeint.
4.1 Addition Operator
The “+” operator returns the sum of two numbers. In this step, I will create AddtionOperatorTest class which demonstrates how to add two numbers of type: int, byte, short, long, float, and double.
AdditionOperatorTest.java
package jcg.zheng.demo.mathoperator.arithmetic;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class AdditionOperatorTest {
@Test
public void byte_addition_arithmetic_operator() {
byte b1 = 1;
byte b2 = 2;
byte sum = (byte) (b1 + b2);
assertEquals(3, sum);
// autoboxing
Byte B1 = Byte.valueOf(b1);
Byte B2 = Byte.valueOf(b2);
assertEquals(3, B1 + B2);
}
@Test
public void double_addition_arithmetic_operator() {
double d1 = 10.01;
double d2 = 20.05;
double sum = d1 + d2;
assertEquals(30.06, sum, 2);
// autoboxing
Double D1 = Double.valueOf(d1);
Double D2 = Double.valueOf(d2);
assertEquals(30.06, D1 + D2, 2);
}
@Test
public void double_float() {
double d = 12.234;
float f = 10.1f;
double sum = d + f;
assertEquals(22.334, sum, 3);
}
@Test
public void double_int() {
double d = 12.234;
int i = 10;
double sum = d + i;
assertEquals(22.234, sum, 3);
}
@Test
public void float_addition_arithmetic_operator() {
float num1 = 10.01f;
float num2 = 20.05f;
float sum = num1 + num2;
assertEquals(30.06, sum, 2);
// autoboxing
Float F1 = Float.valueOf(num1);
Float F2 = Float.valueOf(num2);
assertEquals(30.06, F1 + F2, 2);
}
@Test
public void float_int() {
int i = 2;
float f = 10.1f;
float sum = i + f;
assertEquals(12.1f, sum, 1);
}
@Test
public void int_addition_arithmetic_operator() {
int i = 10;
int i2 = 20;
int sum = i + i2;
assertEquals(30, sum);
Integer num1 = Integer.valueOf(i);
Integer num2 = Integer.valueOf(i2);
assertEquals(30, num1 + num2);
}
@Test
public void long_addition_arithmetic_operator() {
long num1 = 10;
long num2 = 20;
long sum = num1 + num2;
assertEquals(30, sum);
Long L1 = Long.valueOf(num1);
Long L2 = Long.valueOf(num2);
assertEquals(30, L1 + L2);
}
@Test
public void long_int() {
int i = 2;
long l = 10000l;
long sum = i + l;
assertEquals(10002l, sum);
}
@Test
public void short_addition_arithmetic_operator() {
short s1 = 1;
short s2 = 2;
short sum = (short) (s1 + s2);
assertEquals(3, sum);
}
@Test
public void byte_add_constants() {
byte sum = 1 + 2;
// the operands 1 and 2 are constants.
// the compiler computes the sum and replaces 1+2 as 3.
assertEquals(3, sum);
}
@Test
public void shorthand() {
int i = 10;
i += 7;
assertEquals(17, i);
}
}Note: at line 14, 120, the “+” operator returns a result of int type because operands are byte and short.
Execute mvn test -Dtest=AdditionOperatorTest and capture the output.
Junit Output
Running jcg.zheng.demo.mathoperator.arithmetic.AdditionOperatorTest Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.109 sec Results : Tests run: 12, Failures: 0, Errors: 0, Skipped: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.579 s [INFO] Finished at: 2019-09-01T16:32:01-05:00 [INFO] ------------------------------------------------------------------------ C:\MaryZheng\Workspaces\jdk12\java-math-demo>
4.2 Subtraction Operator
The “-“ operator returns the difference of two numbers. In this step, I will create SubtractionOperatorTest class to demonstrate the “-” operator usages for the primitive data types: int, byte, short, long, float, and double .
SubtractionOperatorTest.java
package jcg.zheng.demo.mathoperator.arithmetic;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class SubtractionOperatorTest {
@Test
public void byte_subtraction_arithmetic_operator() {
byte num1 = 3;
byte num2 = 2;
byte diff = (byte) (num1 - num2);
assertEquals(1, diff);
}
@Test
public void byte_subtraction_arithmetic_operator_2() {
byte num1 = 1;
byte num2 = 2;
byte diff = (byte) (num1 - num2);
assertEquals(-1, diff);
}
@Test
public void double_subtraction_arithmetic_operator() {
double num1 = 40.09;
double num2 = 20.05;
double diff = num1 - num2;
assertEquals(20.04, diff, 2);
}
@Test
public void double_float() {
double d = 12.234;
float f = 10.1f;
double diff = d - f;
assertEquals(2.134, diff, 3);
}
@Test
public void double_int() {
double d = 12.234;
int i = 10;
double diff = d - i;
assertEquals(2.234, diff, 3);
}
@Test
public void float_subtraction_arithmetic_operator() {
float num1 = 10.08f;
float num2 = 20.05f;
float diff = num1 - num2;
assertEquals(-10.03, diff, 2);
}
@Test
public void float_int() {
int i = 20;
float f = 10.1f;
float diff = i - f;
assertEquals(9.1f, diff, 1);
}
@Test
public void int_subtraction_arithmetic_operator() {
int i = 10;
int i2 = 20;
int diff = i - i2;
assertEquals(-10, diff);
}
@Test
public void long_subtraction_arithmetic_operator() {
long num1 = 10;
long num2 = 20;
long diff = num1 - num2;
assertEquals(-10, diff);
}
@Test
public void long_int() {
int i = 2;
long l = 10000l;
long diff = l - i;
assertEquals(9998l, diff);
}
@Test
public void short_subtraction_arithmetic_operator() {
short num1 = 1;
short num2 = 2;
short diff = (short) (num1 - num2);
assertEquals(-1, diff);
}
@Test
public void byte_add_constants() {
byte diff = 3 - 2;
assertEquals(1, diff);
}
@Test
public void shorthand() {
int i = 10;
i -= 7;
assertEquals(3, i);
}
@Test
public void test_Integer() {
Integer num1 = Integer.valueOf(5);
Integer num2 = Integer.valueOf(6);
assertEquals(-1, num1 - num2);
}
}Execute mvn test -Dtest=SubtractionOperatorTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.mathoperator.arithmetic.SubtractionOperatorTest Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.135 sec Results : Tests run: 14, Failures: 0, Errors: 0, Skipped: 0
4.3 Increment Operator
The “++” operator increases the value by 1 for primitive data types: int, byte, short, long, float, and double. It can be used in front of a variable or after it.
- ++x : increments
xand read the value ofxafterwards - x++ : increments
xand read the value ofxbeforehand
In this step, I will demonstrate the “++” operator usages with Junit test cases.
Note:
- line 15 – the variable
jhas the variablex‘s old value because ofx++. - line 24 – the variable
jhas the variablex‘s new value because of++x
IncrementOperatorTest.java
package jcg.zheng.demo.mathoperator.arithmetic;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class IncrementOperatorTest {
@Test
public void test_increment_post() {
int i = 0;
int j = i++;
assertEquals(1, i);
assertEquals(0, j);
}
@Test
public void test_increment_pre() {
int i = 0;
int j = ++i;
assertEquals(1, i);
assertEquals(1, j);
}
@Test
public void byte_increment_arithmetic_operator() {
byte b = 1;
b++;
assertEquals(2, b);
}
@Test
public void double_increment_arithmetic_operator() {
double d = 10.01;
d++;
assertEquals(11.01, d, 2);
}
@Test
public void float_increment_arithmetic_operator() {
float f = 10.01f;
f++;
assertEquals(11.01, f, 2);
}
@Test
public void int_increment_arithmetic_operator() {
int i = 10;
i++;
assertEquals(11, i);
}
@Test
public void long_increment_arithmetic_operator() {
long l = 10;
l++;
assertEquals(11, l);
}
@Test
public void short_increment_arithmetic_operator() {
short s = 1;
s++;
assertEquals(2, s);
}
}Execute mvn test -Dtest=IncrementOperatorTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.mathoperator.arithmetic.IncrementOperatorTest Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.121 sec Results : Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
4.4 Decrement Operator
The “–” operator returns the number by subtracting 1 from it. It also can be used in front of or after a variable (int, byte, short, long, float, double).
--x: decrementsxand read the value ofxafterwardsx--: decrementsxand read the value ofxbeforehand
In this step, I will demonstrate the “–” operator usages with Junit test cases. Please verify the highlighted assertion statements.
DecrementOperatorTest.java
package jcg.zheng.demo.mathoperator.arithmetic;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class DecrementOperatorTest {
@Test
public void test_decrement_post() {
int i = 0;
int j = i--;
assertEquals(-1, i);
assertEquals(0, j);
}
@Test
public void test_decrement_pre() {
int i = 0;
int j = --i;
assertEquals(-1, i);
assertEquals(-1, j);
}
@Test
public void byte_decrement_arithmetic_operator() {
byte b = 1;
b--;
assertEquals(0, b);
}
@Test
public void double_decrement_arithmetic_operator() {
double d = 10.01;
d--;
assertEquals(9.01, d, 2);
}
@Test
public void float_decrement_arithmetic_operator() {
float f = 10.01f;
f--;
assertEquals(9.01, f, 2);
}
@Test
public void int_decrement_arithmetic_operator() {
int i = 10;
i--;
assertEquals(9, i);
}
@Test
public void long_decrement_arithmetic_operator() {
long l = 10;
l--;
assertEquals(9, l);
}
@Test
public void short_decrement_arithmetic_operator() {
short s = 1;
s--;
assertEquals(0, s);
}
}Execute mvn test -Dtest=DecrementOperatorTest and capture the output.
Junit Output
Running jcg.zheng.demo.mathoperator.arithmetic.DecrementOperatorTest Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.106 sec Results : Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.158 s [INFO] Finished at: 2019-09-01T16:35:06-05:00 [INFO] ------------------------------------------------------------------------ C:\MaryZheng\Workspaces\jdk12\java-math-demo>
4.5 Multiplication Operator
The “*” operator returns the product of two numbers. In this step, I will demonstrate the “*” operator usages with Junit test cases:
MultiplicationOperatorTest.java
package jcg.zheng.demo.mathoperator.arithmetic;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MultiplicationOperatorTest {
@Test
public void byte_multiplication_arithmetic_operator() {
byte num1 = 1;
byte num2 = 2;
byte product = (byte) (num1 * num2);
assertEquals(2, product);
}
@Test
public void double_multiplication_arithmetic_operator() {
double num1 = 10.01;
double num2 = 20.05;
double product = num1 * num2;
assertEquals(200.71, product, 2);
}
@Test
public void double_float() {
double d = 12.234;
float f = 10.1f;
double product = d * f;
assertEquals(123.563, product, 3);
}
@Test
public void double_int() {
double d = 12.234;
int i = 10;
double product = d * i;
assertEquals(122.234, product, 3);
}
@Test
public void float_multiplication_arithmetic_operator() {
float num1 = 10.01f;
float num2 = 20.05f;
float product = num1 * num2;
assertEquals(200.71, product, 2);
}
@Test
public void float_int() {
int i = 2;
float f = 10.1f;
float product = i * f;
assertEquals(20.2f, product, 1);
}
@Test
public void int_multiplication_arithmetic_operator() {
int i = 10;
int i2 = 20;
int product = i * i2;
assertEquals(200, product);
}
@Test
public void long_multiplication_arithmetic_operator() {
long num1 = 10;
long num2 = 20;
long product = num1 * num2;
assertEquals(200, product);
}
@Test
public void long_int() {
int i = 2;
long l = 10000l;
long product = i * l;
assertEquals(20000l, product);
}
@Test
public void short_multiplication_arithmetic_operator() {
short num1 = 1;
short num2 = 2;
short product = (short) (num1 * num2);
assertEquals(2, product);
}
@Test
public void byte_add_constants() {
byte product = 1 * 2;
//the operands 1 and 2 are compile time constants. Therefore, the compiler computes the product as compile time and replaces 1*2 as 3.
assertEquals(2, product);
}
@Test
public void shorthand() {
int i = 10;
i *= 7;
assertEquals(70, i);
}
@Test
public void test_Integer() {
Integer num1 = Integer.valueOf(5);
Integer num2 = Integer.valueOf(6);
assertEquals(30, num1 * num2);
}
}Execute mvn test -Dtest=MultiplicationOperatorTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.mathoperator.arithmetic.MultiplicationOperatorTest Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.12 sec Results : Tests run: 13, Failures: 0, Errors: 0, Skipped: 0
4.6 Division Operator
The “/” operator returns the quotient when performing the division on the two numbers. In this step, I will demonstrate the “/” operator usages with Junit test cases:
Note: the “/” operator does the integer division, so the remainder is thrown away. See highlighted statements as examples.
DivisionOperatorTest.java
package jcg.zheng.demo.mathoperator.arithmetic;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class DivisionOperatorTest {
@Test
public void byte_division_arithmetic_operator() {
byte num1 = 4;
byte num2 = 2;
byte division = (byte) (num1 / num2);
assertEquals(2, division);
}
@Test
public void byte_division_arithmetic_operator_2() {
byte num1 = 4;
byte num2 = 3;
byte division = (byte) (num1 / num2);
assertEquals(1, division);
}
@Test
public void byte_division_arithmetic_operator_3() {
byte num1 = 3;
byte num2 = 4;
byte division = (byte) (num1 / num2);
assertEquals(0, division);
}
@Test
public void double_division_arithmetic_operator() {
double num1 = 10.02;
double num2 = 3;
double division = num1 / num2;
assertEquals(3.34, division, 2);
}
@Test
public void double_float() {
double d = 12.234;
float f = 10f;
double division = d / f;
assertEquals(1.223, division, 3);
}
@Test
public void double_int() {
double d = 12.234;
int i = 10;
double division = d / i;
assertEquals(1.223, division, 3);
}
@Test
public void float_division_arithmetic_operator() {
float num1 = 10.02f;
float num2 = 2f;
float division = num1 / num2;
assertEquals(5.01, division, 2);
}
@Test
public void float_int() {
int i = 2;
float f = 10.1f;
float division = f / i;
assertEquals(5.05f, division, 2);
}
@Test
public void int_division_arithmetic_operator() {
int i = 40;
int i2 = 20;
int division = i / i2;
assertEquals(2, division);
}
@Test
public void long_division_arithmetic_operator() {
long num1 = 60;
long num2 = 20;
long division = num1 / num2;
assertEquals(3, division);
}
@Test
public void long_int() {
int i = 2;
long l = 10000l;
long division = l / i;
assertEquals(5000l, division);
}
@Test
public void short_division_arithmetic_operator() {
short num1 = 1;
short num2 = 2;
short division = (short) (num1 / num2);
assertEquals(0, division);
}
@Test
public void byte_add_constants() {
byte division = 1 / 2;
assertEquals(0, division);
}
@Test
public void shorthand() {
int i = 10;
i /= 2;
assertEquals(5, i);
}
@Test
public void test_Integer() {
Integer num1 = Integer.valueOf(13);
Integer num2 = Integer.valueOf(6);
assertEquals(2, num1 / num2);
}
}Execute mvn test -Dtest=DivisionOperatorTest and capture the output.
Junit Output
Running jcg.zheng.demo.mathoperator.arithmetic.DivisionOperatorTest Tests run: 15, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.112 sec Results : Tests run: 15, Failures: 0, Errors: 0, Skipped: 0
4.7 Remainder Operator
The “%” operator returns the remainder of two numbers after performing division on two numbers. In this step, I will demonstrate the “%” operator usages with Junit test cases:
RemainderOperatorTest.java
package jcg.zheng.demo.mathoperator.arithmetic;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class RemainderOperatorTest {
@Test
public void byte_remainer_arithmetic_operator() {
byte num1 = 1;
byte num2 = 2;
byte remainer = (byte) (num1 % num2);
assertEquals(1, remainer);
}
@Test
public void double_remainer_arithmetic_operator() {
double num1 = 21;
double num2 = 5;
double remainer = num1 % num2;
assertEquals(1, remainer, 2);
}
@Test
public void double_float() {
double d = 14;
float f = 3f;
double remainer = d % f;
assertEquals(2, remainer, 0);
}
@Test
public void double_int() {
double d = 12.234;
int i = 10;
double remainer = d % i;
assertEquals(2.234, remainer, 3);
}
@Test
public void float_remainer_arithmetic_operator() {
float num1 = 100f;
float num2 = 20f;
float remainer = num1 % num2;
assertEquals(0, remainer, 2);
}
@Test
public void float_int() {
int i = 2;
float f = 10.1f;
float remainer = i % f;
assertEquals(2f, remainer, 1);
}
@Test
public void int_remainer_arithmetic_operator() {
int i = 10;
int i2 = 20;
int remainer = i % i2;
assertEquals(10, remainer);
}
@Test
public void long_remainer_arithmetic_operator() {
long num1 = 10;
long num2 = 20;
long remainer = num1 % num2;
assertEquals(10, remainer);
}
@Test
public void long_int() {
int i = 2;
long l = 10000l;
long remainer = i % l;
assertEquals(2, remainer);
}
@Test
public void short_remainer_arithmetic_operator() {
short num1 = 1;
short num2 = 2;
short remainer = (short) (num1 % num2);
assertEquals(1, remainer);
}
@Test
public void byte_add_constants() {
byte remainer = 1 % 2;
assertEquals(1, remainer);
}
@Test
public void shorthand() {
int i = 10;
i %= 7;
assertEquals(3, i);
}
@Test
public void test_Integer() {
Integer num1 = Integer.valueOf(5);
Integer num2 = Integer.valueOf(6);
assertEquals(5, num1 % num2);
}
}Execute mvn test -Dtest=RemainderOperatorTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.mathoperator.arithmetic.RemainderOperatorTest Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.112 sec Results : Tests run: 13, Failures: 0, Errors: 0, Skipped: 0
4.8 Ternary Operator
The ternary operator consists of a condition that evaluates to either true or false, plus a value that is returned if the condition is true and another value that is returned if the condition is false.
In this step, I will demonstrate the “?:” operator usages with Junit test cases.
TernaryOperatorTest.java
package jcg.zheng.demo.mathoperator.arithmetic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class TernaryOperatorTest {
@Test
public void test_ternary() {
assertTrue(allowToDrink(29));
assertEquals("Enjoying", greetingMsgDrink(28));
assertFalse(allowToDrink(20));
}
private boolean allowToDrink(int age) {
boolean meetMLDA = (age >= 21) ? true : false;
return meetMLDA;
}
private String greetingMsgDrink(int age) {
String meetMLDA = (age >= 21) ? "Enjoying" : "Please wait until you are 21.";
return meetMLDA;
}
}
Execute mvn test -Dtest=TernaryOperatorTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.mathoperator.arithmetic.TernaryOperatorTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.121 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
5. Relational Operators
Java language provides the following relational operators to return a boolean value when comparing two operands belong to the primitive data type.
== | returns a true value if the two operands are equal |
!= | returns a false value if the two operands are not equal |
> | returns true if the left operand is greater than the right operand |
< | returns true if the left operand is smaller than the right operand |
>= | likes the > operator but including equals condition |
<= | likes the < operator but including equals condition |
5.1 Equals Operator
The “==” operator returns the memory address comparison with two variables. In this step, I will demonstrate the following user cases:
- line 69 , 70: two
Stringliterals refer to the same object, so both"=="andequalsreturntrue. - line 77, 85 : “==” return
falsewhen comparing two new instances ofPOJOandPOJOHasEquals - line 78: “
equals” returnfalsewhen comparing two new instances ofPOJO - line 86: “
equals” returnstruewhen comparing two new instances ofPOJOHasEquals.
EqualsOperatorTest.java
package jcg.zheng.demo.mathoperator.relational;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import jcg.zheng.demo.data.POJO;
import jcg.zheng.demo.data.POJOHasEquals;
public class EqualsOperatorTest {
@Test
public void same_int_value_should_equalsto_eachother() {
int i1 = 2;
int i2 = 2;
assertTrue(i1 == i2);
assertFalse(i2 == 1);
Integer num1 = Integer.valueOf(i1);
Integer num2 = Integer.valueOf(i2);
assertTrue(num1 == num2);
}
@Test
public void same_byte_value_should_equalsto_eachother() {
byte i1 = 2;
byte i2 = 2;
assertTrue(i1 == i2);
assertFalse(i2 == 1);
}
@Test
public void same_short_value_should_equalsto_eachother() {
short i1 = 2;
short i2 = 2;
assertTrue(i1 == i2);
assertFalse(i2 == 1);
}
@Test
public void same_long_value_should_equalsto_eachother() {
long i1 = 2;
long i2 = 2;
assertTrue(i1 == i2);
assertFalse(i2 == 1);
}
@Test
public void same_float_value_should_equalsto_eachother() {
float i1 = 2.3f;
float i2 = 2.3f;
assertTrue(i1 == i2);
}
@Test
public void same_double_value_should_equalsto_eachother() {
double i1 = 20.0;
double i2 = 20.00;
assertTrue(i1 == i2);
}
@Test
public void same_String_value_should_equalsto_eachother() {
String s1 = "Mary";
String s2 = "Mary";
assertTrue(s1 == s2);
assertTrue(s1.equals(s2));
}
@Test
public void same_new_instance_of_POJO_not_equalsto_eachother() {
POJO p1 = new POJO();
POJO p2 = new POJO();
assertFalse(p1 == p2);
assertFalse(p1.equals(p2));
}
@Test
public void same_new_instance_of_POJOHasEquals_not_equalsto_eachother() {
POJOHasEquals p1 = new POJOHasEquals("Mary");
POJOHasEquals p2 = new POJOHasEquals("Mary");
assertFalse(p1 == p2);
// Note because the overwrite equals. these two object return true from equals()
assertTrue(p1.equals(p2));
}
}
Execute mvn test -Dtest=EqualsOperatorTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.mathoperator.relational.EqualsOperatorTest Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.116 sec Results : Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
5.2 Not Equal Operator
The “!=” operator is the counterpart of the “==” operator. In this step, I will demonstrate with Junit test class.
Note:
- line 70: two
Stringliterals refer to the same object, so"!="returnsfalse. - line 74 : “!=” return
truewhen comparing literal String to thenewString - line 82: “!=” return
truewhen comparing two new instances ofPOJOfrom default constructor - line 90: “!=” returns
truewhen comparing two new instances ofPOJOHasEquals.
NotEqualsOperatorTest.java
package jcg.zheng.demo.mathoperator.relational;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import jcg.zheng.demo.data.POJO;
import jcg.zheng.demo.data.POJOHasEquals;
public class NotEqualsOperatorTest {
@Test
public void same_int_resutls_false_for_notequalsto_operator() {
int i1 = 2;
int i2 = 2;
assertFalse(i1 != i2);
assertFalse(i2 != 2);
Integer num1 = Integer.valueOf(i1);
Integer num2 = Integer.valueOf(i2);
assertFalse(num1 != num2);
}
@Test
public void same_byte_resutls_false_for_notequalsto_operator() {
byte i1 = 2;
byte i2 = 2;
assertFalse(i1 != i2);
assertTrue(i2 != 1);
}
@Test
public void same_short_resutls_false_for_notequalsto_operator() {
short i1 = 2;
short i2 = 2;
assertFalse(i1 != i2);
assertTrue(i2 != 1);
}
@Test
public void same_long_resutls_false_for_notequalsto_operator() {
long i1 = 2;
long i2 = 2;
assertFalse(i1 != i2);
assertTrue(i2 != 1);
}
@Test
public void same_float_resutls_false_for_notequalsto_operator() {
float i1 = 2.3f;
float i2 = 2.3f;
assertFalse(i1 != i2);
}
@Test
public void same_double_resutls_false_for_notequalsto_operator() {
double i1 = 20.0;
double i2 = 20.00;
assertFalse(i1 != i2);
}
@Test
public void same_literal_String_resutls_false() {
//liternal String are same if the values are same
String s1 = "Mary";
String s2 = "Mary";
assertFalse(s1 != s2);
//s3 uses new keyword, it will have a new instance
String s3 = new String("Mary");
assertTrue(s1 != s3);
}
@Test
public void test_notequaltoOperator_POJO() {
POJO p1 = new POJO();
POJO p2 = new POJO();
assertTrue(p1 != p2);
}
@Test
public void test_notequaltoOperator_POJOHasEquals_default() {
POJOHasEquals p1 = new POJOHasEquals();
POJOHasEquals p2 = new POJOHasEquals();
assertTrue(p1 != p2);
}
@Test
public void test_notequaltoOperator_POJOHasEquals() {
POJOHasEquals p1 = new POJOHasEquals("Mary");
POJOHasEquals p2 = new POJOHasEquals("Mary");
assertTrue(p1 != p2);
}
}
Execute mvn test -Dtest=NotEqualsOperatorTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.mathoperator.relational.NotEqualsOperatorTest Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.128 sec Results : Tests run: 10, Failures: 0, Errors: 0, Skipped: 0
6. String Operator
The “+” operator is used to concatenate string. In this step, I will demonstrate several ways to use it:
- Both operands are
Stringvariables - Only one operand is
Stringvariable, the other is a primitive type - Only one operand is
Stringvariable, the other is a constant
StringOperatorTest.java
package jcg.zheng.demo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;
public class StringOperatorTest {
@Test
public void addition_concatenate_operator() {
String msg1 = "Hello";
String msg2 = " World!";
assertEquals("Hello World!", msg1 + msg2);
}
@Test
public void addition_concatenate_operator_hybrid() {
int num = 10;
String msg = "Hello ";
assertEquals("Hello 10", msg + num);
}
@Test
public void addition_concatenate_operator_hybrid_2() {
String numStr = "10.00";
String msg = "10.00 ";
assertEquals("10.00 10.00", msg + numStr);
}
@Test
public void mixer_constant() {
//1, 2, 3 are constants
assertEquals(6, 1 + 2 + 3);
int one = 1;
String three = "3";
// 2 is the constant, so one+2 is 3
assertEquals("33", one + 2 + three);
assertNotEquals("123", one + 2 + three);
assertEquals(6, 1 + 2 + 3);
}
@Test
public void with_null() {
String str1 = "Hello";
String str2 = null;
assertEquals("Hellonull", (str1 + str2)); // String str2 is null, the compiler replaces it will string “null”.
assertNotEquals("Hello", str1 + str2);
}
@Test
public void with_boolean() {
String msg = "Hello world!";
assertEquals("Hello world!true", msg + true);
assertEquals("Hello world!false", msg + false);
}
}Note:
- line 41: variable
oneis type ofint, it first evaluates with constant 2 to get value 3, then concatenates with variablethree, so the final result is “33” - line 51 – a
nullobject displays asnull - line 58 – a
booleanvariable oftruedisplays astrue - line 59 – a
booleanvariable offalsedisplays asfalse
Execute mvn test -Dtest=StringOperatorTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.StringOperatorTest Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.181 sec Results : Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
7. Operator Precedence
The Java math operators have a natural operator precedence which is same as the precedence of standard math operators.
The math operators * and / for multiplication and division take precedence over the + and - operators. That means, that multiplications and divisions are evaluated before addition and subtraction in math expressions. In case there are multiple * and / operators they will be calculated from left to right.
In this step, I will create a Junit test to show the order of precedence.
OperatorPrecedenceTest.java
package jcg.zheng.demo;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class OperatorPrecedenceTest {
@Test
public void parentheses_is_first() {
int result = 100 * 100 / 5 + 200 * 3 / 2 + 6 * (4 % 5);
assertEquals(2324, result);
}
@Test
public void test_OperatorPrecedence() {
int result = 100 / 5 * 100 + 200 * 3 / 2 + 6 * 4 % 5;
assertEquals(2304, result);
}
@Test
public void from_left_to_right() {
int cal = 1 * 9 % 8 * 3 * 5 / 3;
assertEquals(5, cal);
}
@Test
public void addion_yields() {
int cal = 6 + 3 * 5 / 3;
assertEquals(11, cal);
}
@Test
public void minus_yields() {
int cal = 6 - 3 * 5 % 3;
assertEquals(6, cal);
}
}
Execute mvn test -Dtest=OperatorPrecedenceTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.OperatorPrecedenceTest Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.24 sec Results : Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
8. Java Math Class
The Java Math class provides static methods to perform more advanced mathematical calculations than what the basic Java math operators provide.
In this step, I will create a Junit test class to demonstrate advanced calculation methods:
abs– returns the absolute value of the argumentfloor– returns the largest value based on the argumentsceil– returns the smallest value based on the argumentsmin– returns the smaller of two valuesmax– returns the larger of two values- pow – returns the value of the first argument raised to the power of the second argument
log10– returns the base 10 logarithm of adoublevaluesqrt– returns the correctly rounded positive square root of adoublevalue
MathStaticMethodsTest.java
package jcg.zheng.demo;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MathStaticMethodsTest {
@Test
public void test_abs() {
assertEquals(10, Math.abs(10));
assertEquals(20, Math.abs(-20));
}
@Test
public void test_ceil() {
assertEquals(8.0, Math.ceil(7.343), 0);
}
@Test
public void test_floor() {
assertEquals(7.0, Math.floor(7.343), 0);
}
@Test
public void test_min() {
assertEquals(8, Math.min(8, 17.343), 0);
}
@Test
public void test_max() {
assertEquals(17.343, Math.max(8, 17.343), 0);
}
@Test
public void test_pow() {
assertEquals(9, Math.pow(3, 2), 0);
}
@Test
public void test_pi() {
double area = Math.floor(Math.PI * Math.pow(10, 2));
assertEquals(314, area, 0);
}
@Test
public void test_sqrt() {
double sroot = Math.sqrt(16);
assertEquals(4, sroot, 0);
}
@Test
public void test_log10() {
double logV = Math.log10(100);
assertEquals(2, logV, 0);
}
@Test
public void test_sin() {
assertEquals(0.5, Math.sin(60), 1);
}
@Test
public void test_cos() {
assertEquals(0.5, Math.cos(30), 1);
}
@Test
public void test_log() {
assertEquals(1, Math.log(Math.E), 0);
assertEquals(2, Math.log(Math.pow(Math.E, 2)), 0);
assertEquals(2, Math.log(Math.exp(2)), 0);
}
@Test
public void test_constants() {
System.out.println("Pi=" + Math.PI);
System.out.println("E=" + Math.E);
}
@Test
public void test_exp() {
assertEquals(2, Math.log(Math.exp(2)), 0);
}
}
Execute mvn test -Dtest=MathStaticMethodsTest and capture the output.
Junit Output
------------------------------------------------------- T E S T S ------------------------------------------------------- Running jcg.zheng.demo.MathStaticMethodsTest Pi=3.141592653589793 E=2.718281828459045 Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.122 sec Results : Tests run: 14, Failures: 0, Errors: 0, Skipped: 0
9. Summary
In this example, I demonstrated how to use the build-in math operators and Math static methods to perform arithmetic, relational, and other advanced mathematics operations.
10. Download the Source Code
This example consists of a Maven project which uses Math class and built-in Math operators.
You can download the full source code of this example here: Java Math Operators and Math Class Tutorial
