A program is a set of instructions given to a computer. These instructions initiate some action and hence sometimes called executable instructions. In Java programs, the executable instructions are specified through methods or functions.

A method is a sequence of some declaration statements and executable statements. As Java is strictly object-oriented, any action can take place through methods and have to exist as a part of a class.

method in java

Why Methods?

There are at least three reasons why we use methods

  • To allow us to cope with complex problem
  • To hide low-level details that otherwise obscure and confuse
  • To reuse portions of code.

The general form of a method is –

type name (parameter list) {

// body of method


Here type specifies the type of data returned by the method. This can be any valid type, including class type that you create. If the method does not return a value, then its return type must be void.

The name of the method is specified by name. This can be legal identifier other than those already used by other items within the current scope.

The parameter list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty.

Methods that have a return type other than void return a value to the calling routine using the following form of return statements

Return value;

Here, value is the value returned.


// This program includes a method inside the box class.

class Box {

double width ;

double height;

double depth ;

// display volume of a box

Void volume () {

System.out.print(“Volume is : ” ) ;

System.out.println(width * height * depth );

Class BoxDemo {

public static void main ( String args[] ) {

Box mybox1 = new Box() ;

Box mybox2 = new Box() ;

// assign values to mybox1’s instance variable

mybox1.width = 15 ;

mybox1.height = 30 ;

mybox1.depth = 40 ;

/* assign different values to mybox2’s instance variables */

mybox2.width = 4 ;

mybox2.height = 6 ;

mybox2.depth = 10 ;

// display volume of first box

mybox1.volume() ;

// display volume of second box

mybox2.volume() ;



Output –

This program generates the following output.

Volume is 18000.0

Volume is 240.0

Description –

Recommended Post   Overview Of Java

The first line here invokes the volume() method on mybox1. That is, it calls volume() relative to the mybox1 object, using the object’s name followed by the dot operator.

Thus, the call to mybox1..volume() displays the volume of the box defined by mybox1, and the call to mybox2.volume() displays the volume of the box defined by mybox2.

Each time volume() is invoked, it displays the volume for the specified box.


Please enter your comment!
Please enter your name here