Java Methods

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 {/* ww  w .j a va  2 s .  co  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:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures