Introduction

     One of the fundamental concepts in geometry and computer science is calculating the distance between two points in a plane. This concept is often used in various applications like computer graphics, mapping systems, and even in some algorithms. In this blog post, we will discuss how to calculate the distance between two points in a 2D plane using Java.


Code

    
        
        import java.util.*;
        import java.io.*;
        import java.text.DecimalFormat;
        
        public class CalculateDistance {
            public static void main(String args[]) throws IOException {
                DataInputStream s = new DataInputStream(System.in);
                DecimalFormat decForm = new DecimalFormat("0.##");
                double x1 = 0, x2 = 0, y1 = 0, y2 = 0, distance = 0;
        
                // Input coordinates
                System.out.println("Enter x1:");
                x1 = Integer.parseInt(s.readLine());
        
                System.out.println("Enter x2:");
                x2 = Integer.parseInt(s.readLine());
        
                System.out.println("Enter y1:");
                y1 = Integer.parseInt(s.readLine());
        
                System.out.println("Enter y2:");
                y2 = Integer.parseInt(s.readLine());
        
                // Calculate distance using the formula
                distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
                
                // Output the result
                System.out.println("The distance is: " + decForm.format(distance));
            }
        }            
        
        


Output


        Enter x1:
        10
        Enter x2:
        20
        Enter y1:
        15
        Enter y2:
        30
        The distance is: 10.72
        

Explanation

1. Imports and Declarations:
    We import necessary classes for input handling (DataInputStream), formatting the output (DecimalFormat), and using mathematical functions (Math).
2. User Input:
     The program prompts the user to enter the coordinates for both points (𝑥1,𝑦1)(x1,y1) and (𝑥2,𝑦2)(x2,y2). The DataInputStream reads these values as strings, and Integer.parseInt converts them to integers.
3. Distance Calculation:
    The distance is calculated using the distance formula, leveraging Java’s Math.sqrt and Math.pow methods to perform the square root and power operations.
4 Formatting the Output:
    The DecimalFormat class is used to format the output to two decimal places for a more readable result.
5. Displaying the Result:
    Finally, the program outputs the calculated distance to the console.


Conclusion

    This Java program is a straightforward implementation of the distance formula, showing how basic mathematical concepts can be translated into code. Understanding how to manipulate and calculate data in this way is an essential skill in programming, and mastering it will open doors to more complex problem-solving techniques.