Java Double Equals Method

JavaJavaBeginner
Practice Now

Introduction

In Java, the equals() method is used to compare the value of a Double object currently in use with the value of a parameter. This method is built in the Double class, and allows for easy comparison of Double values.

Add the code snippet

Add the following code to the DoubleEquals.java file:

import java.util.Scanner;

public class DoubleEquals {
    public static void main(String[] args) {
        try {
          	Scanner sc = new Scanner(System.in);
            System.out.print("Enter first double value: ");
            Double n1 = sc.nextDouble();
            System.out.print("Enter second double value: ");
            Double n2 = sc.nextDouble();
            boolean equal = n1.equals(n2);
            if (equal) {
                System.out.println(n1 + " equals " + n2);
            } else {
                System.out.println(n1 + " does not equals " + n2);
            }
        } catch (Exception e) {
            System.out.println("Invalid input!!Please check");
        }
    }
}

This code snippet will ask the user to input two double values and then compare them using the Double Equals method. If the values are equal, it will print a message saying so; otherwise it will print a message saying that they are not equal.

Compile and run the code

In your terminal, navigate to the ~/project directory, and compile the code by running the following command:

javac DoubleEquals.java

If there are no errors, you can run your program using the following command:

java DoubleEquals

Your program will now run, and it will ask you to input two double values. After you have done so, it will print a message saying whether they are equal or not.

Summary

In this lab, we learned how to use the Java Double Equals method to compare double values in Java. We created a Java program that asks the user to input two double values and then uses the Double Equals method to compare them. If they are equal, the program prints a message saying so; otherwise, it prints a message saying that they are not equal.

Other Java Tutorials you may like