Java Day 7: Methods and Basic Object-Oriented Concepts

Goal of this Day

Today you will learn:

By the end, you will be able to structure your code using methods and create simple objects.

Step 1: Defining and Calling Methods

A method is a block of code that performs a specific task.


public static int add(int x, int y) {
    return x + y;
}

To call a method:


int result = add(5, 3);

Explanation:

Step 2: Parameters and Return Values

Parameters allow you to pass data into methods.

Return values send results back to the caller.


public static int multiply(int a, int b) {
    return a * b;
}

Step 3: Introduction to Classes and Objects

Java is an object-oriented programming language.

Example:


class Dog {
    String name;
    int age;

    void bark() {
        System.out.println("Woof!");
    }
}

Practice


public class Calculator {
    public static int add(int x, int y) {
        return x + y;
    }

    public static void main(String[] args) {
        int sum = add(5, 3);
        System.out.println("Sum: " + sum);
    }
}

Exercise

Create a class Dog with attributes and a method.

Steps:

Example:


public class Dog {
    String name;
    int age;

    void bark() {
        System.out.println("Woof!");
    }

    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.name = "Buddy";
        myDog.age = 3;

        myDog.bark();
    }
}