Methods

A Java method represent the behavior of an object. It usually consists of logic to perform some operation or to manipulate the state of an object. A method can receive input and return an output. A method name usually be a verb or an action that it performs.

Accepting and Returning Values from a Method

package com.techstackjournal.app.types;

public class ArithmeticOperation {

	double operandOne;
	double operandTwo;

	public double getOperandOne() {
		return operandOne;
	}

	public void setOperandOne(double var1) {
		this.operandOne = var1;
	}

	public double getOperandTwo() {
		return operandTwo;
	}

	public void setOperandTwo(double var2) {
		this.operandTwo = var2;
	}

	public double add() {
		return operandOne + operandTwo;
	}

	public double subtract() {
		return operandOne - operandTwo;
	}

	public double divide() {
		return operandOne / operandTwo;
	}

	public double multiply() {
		return operandOne * operandTwo;
	}

}

In the above class, setOperandOne and setOperandTwo methods have one double type variable in the parameter list, this signify that these methods require a double type variable when they are called. Both of these methods have return type as void, which signify that these methods doesn’t return any value.

Methods add, subtract, multiply, divide, getOperandOne and getOperandTwo methods have double as their return type, that signifies that these methods will return double to the calling statement. And in fact, these methods return double values using return keyword. The calling statement can assign this returned value into a variable.

package com.techstackjournal.app.main;

import com.techstackjournal.app.types.ArithmeticOperation;

public class ArithmeticApplication {

	public static void main(String[] args) {

		ArithmeticOperation operation = new ArithmeticOperation();
		double result;

		operation.setOperandOne(45);
		operation.setOperandTwo(4);

		result = operation.divide();
		System.out.println("Arithmetic Operation: " + result);

	}

}

Here, setOperandOne and setOperandTwo have been called by sending double type variable. We are also calling divide method which returns a double value. Returned double values is being assigned into a result variable.

Points to Remember

  • Method names are usually verbs
  • Method declaration should consist of what type of parameters it needs and what type of value it return
  • Method returns a single value
  • The return value could be a primitive type, an object’s reference or an array’s reference
  • If a method doesn’t return anything the return type should be specified as void.
  • Method should begin with curly bracket and end with curly bracket
  • When methods are invoked, control transfers to that method and once the operation is completed, control transfers back to the calling statement