Introduction
In this lab, you will learn how to check if a number is zero in Java. This fundamental skill is crucial for controlling program flow using conditional statements. We will begin by exploring the use of the equality operator (==) for comparing integer values to zero.
Following that, we will address the specific considerations and potential pitfalls when dealing with floating-point numbers and zero due to precision issues. Finally, we will examine how to perform zero checks when working with Java's wrapper classes for primitive types.
Use Equality Operator for Zero
In this step, we will explore how to check if a number is equal to zero in Java using the equality operator. This is a fundamental operation in programming, often used in conditional statements to control the flow of your program.
In Java, the equality operator is represented by ==. It is used to compare two values and returns true if they are equal, and false otherwise.
Let's create a simple Java program to demonstrate this.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.Replace the entire contents of the file with the following code:
public class HelloJava { public static void main(String[] args) { int number = 0; if (number == 0) { System.out.println("The number is zero."); } else { System.out.println("The number is not zero."); } } }Let's break down this new code:
int number = 0;: This line declares an integer variable namednumberand initializes it with the value0.if (number == 0): This is anifstatement, which is used to make decisions in your code. The condition inside the parentheses(number == 0)checks if the value of thenumbervariable is equal to0.System.out.println("The number is zero.");: This line will be executed only if the conditionnumber == 0istrue.else: This keyword introduces the block of code that will be executed if theifcondition isfalse.System.out.println("The number is not zero.");: This line will be executed only if the conditionnumber == 0isfalse.
Save the file (Ctrl+S or Cmd+S).
Now, let's compile our modified program. In the Terminal, make sure you are in the
~/projectdirectory. You can usecd ~/projectif needed. Then, run:javac HelloJava.javaIf the compilation is successful, you will not see any output.
Finally, let's run our program:
java HelloJavaYou should see the following output:
The number is zero.This confirms that our program correctly checked if the
numbervariable was equal to zero using the==operator.
Now, try changing the value of the number variable to a non-zero value (e.g., int number = 5;), save the file, recompile, and run the program again to see the different output.
Handle Floating-Point Precision
In this step, we will explore a common issue when working with floating-point numbers (numbers with decimal points) in programming: precision. Due to how computers store these numbers, direct equality comparisons using == can sometimes lead to unexpected results.
Let's see this in action.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
public class HelloJava { public static void main(String[] args) { double num1 = 0.1 + 0.2; double num2 = 0.3; System.out.println("num1: " + num1); System.out.println("num2: " + num2); if (num1 == num2) { System.out.println("num1 is equal to num2."); } else { System.out.println("num1 is not equal to num2."); } } }In this code:
- We declare two
doublevariables,num1andnum2.doubleis a data type in Java used for storing floating-point numbers. - We assign
0.1 + 0.2tonum1and0.3tonum2. Mathematically, these should be equal. - We print the values of
num1andnum2to see their exact representation. - We use the
==operator to check ifnum1is equal tonum2.
- We declare two
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaRun the compiled program:
java HelloJavaYou might be surprised by the output:
num1: 0.30000000000000004 num2: 0.3 num1 is not equal to num2.As you can see,
num1is not exactly0.3due to the way floating-point numbers are stored. This is a common issue and why directly comparing floating-point numbers for equality using==is generally discouraged.
To handle this, instead of checking for exact equality, we usually check if the absolute difference between the two numbers is within a very small tolerance (often called an "epsilon").
Let's modify the code to use this approach.
Open
HelloJava.javaagain.Replace the
ifstatement with the following:double epsilon = 0.000001; // A small tolerance if (Math.abs(num1 - num2) < epsilon) { System.out.println("num1 is approximately equal to num2."); } else { System.out.println("num1 is not approximately equal to num2."); }Here:
- We define a small
epsilonvalue. Math.abs(num1 - num2)calculates the absolute difference betweennum1andnum2.- We check if this absolute difference is less than our
epsilon.
- We define a small
Save the file.
Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaNow the output should be:
num1: 0.30000000000000004 num2: 0.3 num1 is approximately equal to num2.This demonstrates the correct way to compare floating-point numbers for practical equality by considering precision limitations.
Test with Wrapper Classes
In this step, we will explore how equality works with Java's wrapper classes. Wrapper classes are special classes that provide a way to use primitive data types (like int, double, boolean) as objects. For example, the wrapper class for int is Integer, and for double is Double.
When comparing objects in Java, the == operator checks if the two variables refer to the exact same object in memory, not if their values are equal. To compare the values of objects, you should use the equals() method.
Let's see how this applies to wrapper classes.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
public class HelloJava { public static void main(String[] args) { Integer intObj1 = new Integer(100); Integer intObj2 = new Integer(100); Integer intObj3 = intObj1; // intObj3 refers to the same object as intObj1 System.out.println("Comparing Integer objects with ==:"); if (intObj1 == intObj2) { System.out.println("intObj1 == intObj2 is true"); } else { System.out.println("intObj1 == intObj2 is false"); } if (intObj1 == intObj3) { System.out.println("intObj1 == intObj3 is true"); } else { System.out.println("intObj1 == intObj3 is false"); } System.out.println("\nComparing Integer objects with equals():"); if (intObj1.equals(intObj2)) { System.out.println("intObj1.equals(intObj2) is true"); } else { System.out.println("intObj1.equals(intObj2) is false"); } if (intObj1.equals(intObj3)) { System.out.println("intObj1.equals(intObj3) is true"); } else { System.out.println("intObj1.equals(intObj3) is false"); } } }In this code:
- We create two
Integerobjects,intObj1andintObj2, with the same value (100) usingnew Integer(). This creates two distinct objects in memory. - We create
intObj3and assignintObj1to it. This meansintObj3andintObj1now point to the same object in memory. - We use
==to compareintObj1withintObj2andintObj3. - We use the
equals()method to compare the values ofintObj1withintObj2andintObj3.
- We create two
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaRun the compiled program:
java HelloJavaThe output should be:
Comparing Integer objects with ==: intObj1 == intObj2 is false intObj1 == intObj3 is true Comparing Integer objects with equals(): intObj1.equals(intObj2) is true intObj1.equals(intObj3) is trueThis output clearly shows the difference:
intObj1 == intObj2isfalsebecause they are different objects in memory, even though their values are the same.intObj1 == intObj3istruebecause they refer to the exact same object.intObj1.equals(intObj2)istruebecause theequals()method compares the values of the objects, which are both 100.intObj1.equals(intObj3)is alsotruebecause they refer to the same object, and their values are the same.
Important Note: For small integer values (typically -128 to 127), Java uses a cache for
Integerobjects. This means thatInteger intObjA = 50; Integer intObjB = 50;might result inintObjA == intObjBbeingtruebecause they might refer to the same cached object. However, relying on this caching behavior for equality checks is not recommended. Always use theequals()method to compare the values of wrapper class objects.
This step highlights the crucial difference between comparing primitive types and objects in Java and the importance of using the equals() method for object value comparison.
Summary
In this lab, we learned how to check if a number is zero in Java. We started by using the fundamental equality operator (==) to compare an integer variable with zero within an if statement. This demonstrated the basic principle of conditional checks based on numerical equality.
We then explored the nuances of handling floating-point numbers and the potential precision issues that arise when comparing them directly to zero using ==. Finally, we examined how to perform zero checks with Java's wrapper classes, understanding how to access and compare the underlying primitive values.



