Java – Instance Methods

Instance Method:

  • Defining a method without static keyword.
  • We must invoke the method using object-reference.

No arguments and No return values method:

class Code
{
            public static void main(String[] args) {
                        Code obj = new Code();
                        obj.fun();
            }
            void fun(){
                        System.out.println(“fun”);
            }
}

With arguments and No return values method:

class Code
{
            static void main(String[] args) {
                        Code obj = new Code();
                        obj.isEven(4);
                        obj.isEven(13);
            }
            static void isEven(int n){
                        if(n%2==0)
                            S.o.p(n + ” is Even”);
                        else
                            S.o.p(n + ” is Not even”);
            }
}

With arguments and with return values method:

class Code
{
            static void main(String[] args) {
                        Code obj = new Code();
                        int r1 = obj.add(10, 20);
                        S.o.p(r1);
            }
            int add(int a, int b){
                        return a+b;
            }
}

No arguments and with return values:

class Code
{
            static void main(String[] args) {
                        Code obj = new Code();
                        double PI = obj.getPI();
                        S.o.p(“PI val : ” + PI);
            }
            double getPI(){
                        double PI = 3.142;
                        return PI;
            }
}
Scroll to Top