Ad

Java Methods

A function inside a class is known as method. A method is use to write a code that can be used many times. It helps in reuseablity of code.

this keyword

Sometimes the variable name used in parameter of a method is same as defined in a class. To distinguish between variables we use this keyword. This keyword refers to the class variable.

Methods inside Main class

class Sum{
    /*
     * public: global
     * static: without object you can access it
     * return c: return type
     * add: method name
     * (int a, int b): parameters
    */
    static int add(int a, int b) { // formal argument
        int c = a+b;
        return c;
    }
    public static void main(String[] args) {
        int x=15, y=20, z;
        z=add(x,y); // actual argument (method call)
        System.out.println("Sum = " + z);
    }
}

Methods outside Main class

In the example, we will create another class and defines a static method in that class.

class MyClass { //user-defined class
    static void message() {
        System.out.println("Method inside user-defined class");
    }
}
public class ClassExample1 {
    public static void main(String[] args) {
        MyClass.message();
    }
}

Example: user-defined non-static method, inside user-defined class

class MyClass { //user-defined class
    void message() {
        System.out.println("Inside User-define class");
    }
}
public class ClassExample {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.message();
    }
}

Example: find Simple Interest using user-defined non-static method, inside user-defined class

class SIClass {
    public float si(float p, float r, float t){
        float s = p*r*t/100;
        return s; 
    }
}
public class SI {
    public static void main(String[] args) {
        SIClass obj = new SIClass();
        float s = obj.si(1000f,5.54f,2f);
        System.out.println("Si = " +s);
    }
}