Purpose of Methods

  • To keep programs organized and readable.
  • To reuse some codes.
  • To break programs into separate logical parts.

Method Template

public static type name (parameters)
{
       method body
}

Example 1

public class Intro
{
    public static void main(String [] args)
    {
         message();
    }

    public static void message()
    {
         System.out.println("Good Day!");
    }
}

Example 2

public class Intro2
{
    public static void main(String [] args)
    {
         System.out.printf("The payment is %d. \n", charge());
    }

    public static int charge()
    {
         return 100;
    }
}

Example 3

public class Intro3
{
    public static void main(String [] args)
    {
         System.out.printf("After tax of $5 is $%.2f. \n", pay(5));

	double keyboard = 89.99;
	double aftertax = pay(keyboard);
	System.out.printf("After tax of keyboard is $%.2f. \n", aftertax);
    }

    public static double pay(double x)
    {
         return x * 1.0925;
    }
}
Click here for example.

Call a method of other class

public class Intro2
{
    public static void main(String [] args)
    {
        System.out.printf("The payment is %d. \n", charge());

	Intro.message();
    }

    public static int charge()
    {
         return 100;
    }
}