0
0
Javaprogramming~7 mins

Procedural vs OOP approach in Java

Choose your learning style9 modes available
Introduction

We use different ways to organize code. Procedural groups steps one after another. OOP groups data and actions together to model real things.

When you want simple step-by-step instructions, like a recipe.
When you want to model real-world objects, like a car or a person.
When your program grows bigger and you want to keep code organized.
When you want to reuse code easily by creating objects.
When you want to protect data and control how it changes.
Syntax
Java
Procedural approach:
// Write functions and call them in order

OOP approach:
// Define classes with data and methods
// Create objects from classes
// Use objects to perform actions

Procedural code focuses on actions and steps.

OOP code focuses on objects that have both data and actions.

Examples
This is a procedural style: a function adds two numbers and main calls it.
Java
public class ProceduralExample {
    public static void main(String[] args) {
        int a = 5;
        int b = 3;
        int sum = add(a, b);
        System.out.println("Sum: " + sum);
    }

    public static int add(int x, int y) {
        return x + y;
    }
}
This is OOP style: a Calculator object holds numbers and adds them.
Java
class Calculator {
    int a, b;

    Calculator(int a, int b) {
        this.a = a;
        this.b = b;
    }

    int add() {
        return a + b;
    }
}

public class OOPExample {
    public static void main(String[] args) {
        Calculator calc = new Calculator(5, 3);
        System.out.println("Sum: " + calc.add());
    }
}
Sample Program

This program shows both ways to add numbers. Procedural uses a simple function. OOP uses a class with data and method.

Java
public class ProceduralVsOOP {

    // Procedural method
    public static int proceduralAdd(int x, int y) {
        return x + y;
    }

    // OOP class
    static class Adder {
        int x, y;

        Adder(int x, int y) {
            this.x = x;
            this.y = y;
        }

        int add() {
            return x + y;
        }
    }

    public static void main(String[] args) {
        // Using procedural approach
        int result1 = proceduralAdd(10, 20);
        System.out.println("Procedural sum: " + result1);

        // Using OOP approach
        Adder adder = new Adder(10, 20);
        int result2 = adder.add();
        System.out.println("OOP sum: " + result2);
    }
}
OutputSuccess
Important Notes

Procedural code is easier for small tasks.

OOP helps manage bigger programs by grouping data and actions.

OOP supports concepts like reuse and protection of data.

Summary

Procedural approach writes step-by-step instructions.

OOP approach models real things as objects with data and actions.

Choose the approach based on program size and needs.