Methods in Java

Methods in Java

by Administrator | 01-Apr-2020

Tags:  Core Java  Methods  Functions


Method is a block of code that helps the user achieve specific functionality. Methods are very important because they help prevent code duplication because we can call them whenever we require that functionality. In Java, a method has to be a part of a class, it cannot be placed on its own.


[Modifier] <Return-Type> <Method-Name> ([<Parameters>]) [Throws] {


Following are the modifiers you can use with a method:

Access Modifier                       

  1. Private
  2. Protected
  3. Public


  1. final
  2. static
  3. strictfp
  4. abstract
  5. synchronized
  6. native

 Depending on the return type there are two types of methods:

  1. method that returns a value.
  2. method that will not return a value.

 Depending on the parameters there are two types of methods:

  1. method with parameters
  2. method without parameters.

Rules for defining a method

  1. The return type of the method should be void if the method is not returning anything. The return type cannot be blank.
  2. For a method with void return type, there is no need to use return statement. It can have an empty return statement without any value like this”
  1. If the method is returning a value, the return type should not be void and should be a data type compatible with the value being expected.
  2. If the method is returning a value, the return statement must be included as the last statement followed by the returning value. For eg.
return string; //where string is a variable evaluating to something
  1. A method can have any number of return statements but conditionally only one of them should evaluate to true. For eg in the below program to check if a number is odd or even there are two return statements but only one of them will be true at a time.
public String oddEven(int num) {
    if (num % 2 == 0) {
        return "Even";
    } else {
        return "Odd";
  1. A method needs to have a parameter(s) if the caller wants to provide a value dynamically to the method. For e.g. in the above program, the text inside the bracket (int num) is called a parameter. The method is of no use without that value.
  2. The caller of the method needs to provide the argument while calling the method if the method being called is having a parameter. For eg in the above method oddEven(), some code should be there which will provide the value of the num variable. Suppose the code is:
  1. If a method has more than one parameters then the datatype, order and the number of arguments must be the same while calling the method. The argument can be of the same or compatible data types.


There are no comments.

Enter a new Comment:

Copyright Šprgrmmng. All rights reserved.