Java Methods

In this chapter you will learn:

  1. What are methods in a class
  2. Syntax for Java methods
  3. Example - How to add a method to a class

Description

Classes usually consist of two things: instance variables and methods. Instance variables are the data part of a class, while the methods defines the behaviours of a class.

Syntax

This is the general form of a method:


type name(parameter-list) { 
   // body of method 
} 

type specifies the type of data returned by the method. If the method does not return a value, its return type must be void. The name of the method is specified by name.

The parameter-list is a sequence of type and identifier pairs separated by commas.

Parameters receives the value of the arguments passed to the method.

If the method has no parameters, then the parameter list will be empty.

Example

Add a method to Box,as shown here:

 
class Box {/*from   w w w.  ja v  a2s  .c o  m*/
  int width;
  int height;
  int depth;
  void calculateVolume() {
    System.out.print("Volume is ");
    System.out.println(width * height * depth);
  }
}

public class Main {

  public static void main(String args[]) {
    Box mybox1 = new Box();
    mybox1.width = 10;
    mybox1.height = 20;
    mybox1.depth = 15;

    mybox1.calculateVolume();

  }
}

This program generates the following output:

Next chapter...

What you will learn in the next chapter:

  1. How to return from a method
  2. Syntax for return value from a method
  3. Example - How to return a value from a method
  4. Example - How to return an object from a method