Methods in Java

A method is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name. Each calculation part of a program is called a method. Methods are logically the same as C's functions, Pascal's procedures and functions, and Fortran's functions and subroutines.
When I wrote System.out.println("Hello World!"); in the first program we were using the System.out.println() method.

The System.out.println() method actually requires quite a lot of code, but it is all stored for us in the System libraries. Thus rather than including that code every time we need to print, we just call the  System.out.println() method.

You can write and call your own methods too. Methods begin with a declaration. This can include three to five parts. First is an optional access specifier which can be public, private or protected. A public method can be called from pretty much anywhere. A private method can only be used within the class where it is defined. A protected method can be used anywhere within the package in which it is defined. Methods that aren't specifically declared public or private are protected by default.
access specifier. We then decide whether the method is or is not static. Static methods have only one instance per class rather than one instance per object. All objects of the same class share a single copy of a static method. By default methods are not static. We finally specify the return type. Next is the name of the method.

Source Code:

class FactorialTest
     {
        //calculates the factorial of that number.
        public static void main(String args[])
        {
            int n;
            int i;
            long result;
            for (i=1; i <=10; i++)
            {
                result = factorial(i);
                 System.out.println(result);
            }
        } // main ends here
    static long factorial (int n)
     {
        int i;
        long result=1;
        for (i=1; i <= n; i++)
        {
            result *= i;
         }
             return result;
     } // factorial ends here
    }

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More