Methods in java

In Java, a method is a block of code that performs a specific task. It can take input in the form of parameters, and it can return output in the form of a return value. Methods are defined inside a class, and they are used to perform specific operations on objects of that class.

Here’s an example of a simple method in Java:

public class Calculator {
    public static int add(int num1, int num2) {
        int result = num1 + num2;
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        int sum = Calculator.add(3, 4);
        System.out.println(sum); // output: 7
    }
}

In this example, we have defined a Calculator class with a static method called add(). This method takes two integer parameters (num1 and num2), adds them together, and returns the result as an integer. We can then call this method in our Main class by using the syntax ClassName.methodName(), passing in the two integer values we want to add.

Java also supports non-static methods, which can be called on an instance of a class rather than on the class itself. Here’s an example:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void sayHello() {
        System.out.println("Hello, my name is " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        person1.sayHello(); // output: Hello, my name is John
    }
}

In this example, we have defined a Person class with a non-static method called sayHello(). This method simply prints out a message that includes the person’s name. We can then call this method on an instance of the Person class by using the syntax objectName.methodName(). In this case, we create a new Person object called person1 and call its sayHello() method.

Share