Java Program to Find Area and Perimeter of a Square

In this tutorial, you will learn how to write a Java program to calculate the area and perimeter of a square. We will explore four different approaches:

  • Basic Approach: Using standard sequential logic in the main method
  • Custom Methods: Using user-defined methods for modular calculations
  • Object-Oriented (OOP): Using classes, constructors, and methods
  • User Input: Using the Scanner class for dynamic user inputs

Let’s explore each approach step-by-step with examples.

Basic Approach to Find Area and Perimeter of a Square in Java

Write a Java program to calculate the area and perimeter of a square without taking input from the user and display both results on the console.

Use the following formulas to find the area and perimeter of a square:

  • Area = side × side
  • Perimeter = 4 × side

This is the basic approach, which requires only basic input, variables, multiplication, and output, making it suitable for a beginner learning Java. It calculates the values directly inside the main() method using fixed (hardcoded) variables.

Expected Solution Approach of the Program

You can write this program in four simple steps:

Step 1: Declare and Initialize the Variable

Declare a variable named side of type double to represent the side length of the square, and assign it an initial value.

double side = 5.0;

Step 2: Calculate the Area

Compute the area using the formula Area = side * side:

double area = side * side;

Step 3: Calculate the Perimeter

Compute the perimeter using the formula Perimeter = 4 * side:

double perimeter = 4 * side;

Step 4: Display the Results

Print both calculated values to the console:

System.out.println("Area: " + area);
System.out.println("Perimeter: " + perimeter);

Complete Java Program

Here is the complete program to find the area and perimeter of a square in Java:

public class SquareBasic {
    public static void main(String[] args) {
        // Define the side length of the square
        double side = 5.0;

        // Formula for Area: side * side
        double area = side * side;

        // Formula for Perimeter: 4 * side
        double perimeter = 4 * side;

        // Print the results to the console
        System.out.println("Side Length: " + side);
        System.out.println("Area of Square: " + area);
        System.out.println("Perimeter of Square: " + perimeter);
    }
}

Expected Output:

Side Length: 5.0
Area of Square: 25.0
Perimeter of Square: 20.0

In this example program, we have:

  • Defined a public class named SquareBasic, which serves as the blueprint of the program.
  • Defined the main() method, which serves as the entry point where the Java Virtual Machine (JVM) begins code execution.
  • Declared a floating-point variable named side and assigned it the value 5.0.
  • Calculated the area of the square and stored the resulting value in the area variable.
  • Calculated the perimeter of the square and stored the resulting value in the perimeter variable.
  • Displayed the side length, calculated area, and calculated perimeter on the console.

Using Custom Methods to Find Area and Perimeter of a Square in Java

In this approach, we separate the logic into smaller, reusable blocks of code called methods instead of writing all the formulas inside main(). We create one method to calculate the area and another to calculate the perimeter. This makes the code cleaner, easier to read, and reusable for different values.

Here is the complete program to find the area and perimeter of a square in Java using user-defined methods.

public class SquareMethods {

    // Method to calculate area
    public static double getArea(double side) {
        return side * side;
    }

    // Method to calculate perimeter
    public static double getPerimeter(double side) {
        return 4 * side;
    }

    public static void main(String[] args) {
        double side = 6.5;

        // Call the methods and store the return values
        double area = getArea(side);
        double perimeter = getPerimeter(side);

        // Display results
        System.out.println("Side Length: " + side);
        System.out.println("Area: " + area);
        System.out.println("Perimeter: " + perimeter);
    }
}

Expected Output:

Side Length: 6.5
Area: 42.25
Perimeter: 26.0

In this program code, we have:

  • Defined a user-defined static method that takes the side length as a parameter, computes the area, and returns the result using the return statement.
  • Defined another user-defined static method that takes the side length, computes the perimeter, and returns the value.
  • Declared both methods as static, allowing them to be called directly inside main() without creating an object of the SquareMethods class.
  • Invoked both methods by passing the argument side (with value 6.5) to getArea() and getPerimeter(), then stored the returned values in local variables area and perimeter.
  • Displayed the side length along with the computed area and perimeter on the console. using System.out.println().

Object-Oriented Approach: Using a Constructor and Instance Methods

In this approach, we follow the core principles of Object-Oriented Programming (OOP) by creating a dedicated Square class. We use a constructor to initialize the square’s side length when creating an object and instance methods to calculate its area and perimeter. This approach encapsulates data and behavior together, making the code modular, scalable, and easy to maintain.

Here is the complete program to find the area and perimeter of a square in Java using the object-oriented approach.

class Square {
    // Instance variable representing the state
    private double side;

    // Parameterized constructor to initialize the square's side
    public Square(double side) {
        this.side = side;
    }

    // Instance method to compute area
    public double calculateArea() {
        return this.side * this.side;
    }

    // Instance method to compute perimeter
    public double calculatePerimeter() {
        return 4 * this.side;
    }
}

public class SquareOOP {
    public static void main(String[] args) {
        // Instantiate a Square object with side length 8.0
        Square mySquare = new Square(8.0);

        // Invoke instance methods on the object
        System.out.println("Area: " + mySquare.calculateArea());
        System.out.println("Perimeter: " + mySquare.calculatePerimeter());
    }
}

Expected Output:

Area: 64.0
Perimeter: 32.0

In this example program, we have:

  • Declared a class named Square, which encapsulates the properties and operations of a square within its own custom type.
  • Defined private instance variable to implement data hiding (encapsulation) so the state of the square cannot be altered directly from outside the class.
  • Declared a parameterized constructor, which automatically executes when a new Square object is created; assigns the passed argument to the instance variable using the this keyword.
  • Defined instance methods (calculateArea() and calculatePerimeter()) that compute and return the area and perimeter.
  • Created an instance of the Square class.
  • Invoked mySquare.calculateArea() and mySquare.calculatePerimeter() directly inside System.out.println() to compute and print the results to the terminal.

Java Program to Find Area and Perimeter of a Square Using Scanner

In this approach, instead of hardcoding the side length, we make the program interactive by taking dynamic input directly from the user at runtime. Inside the main method, we use Java’s Scanner class to read the side value entered via the keyboard, calculate the area and perimeter, and print the results to the console.

Here is the complete program code to find the area and perimeter of a square in Java using the Scanner class.

import java.util.Scanner;

public class SquareScanner {
    public static void main(String[] args) {
        // Initialize the Scanner object for keyboard input
        Scanner scanner = new Scanner(System.in);

        // Prompt the user for input
        System.out.print("Enter the side length of the square: ");
        double side = scanner.nextDouble();

        // Calculate area and perimeter
        double area = side * side;
        double perimeter = 4 * side;

        // Display the output
        System.out.println("Area: " + area);
        System.out.println("Perimeter: " + perimeter);

        // Close the scanner to prevent resource leaks
        scanner.close();
    }
}

Expected Output:

Enter the side length of the square: 7.2
Area: 51.84
Perimeter: 28.8

In this example program,

  • We use import java.util.Scanner; to import the class for reading user input.
  • Inside the main() method, Scanner scanner = new Scanner(System.in); creates an instance of the Scanner class.
  • The scanner.nextDouble() method pauses the program, waits for the user to enter a number, and stores it in the side variable.
  • We calculate the area and perimeter of the square using the geometric formulas.
  • The System.out.println() method prints the calculated area and perimeter to the console.
  • The scanner.close() method closes the scanner to prevent resource leaks and free up memory.
DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.