Java Methods With Examples

Java Methods With Examples

Define :

  • Method first letter will always be in small case.
  • A method is a collection of set of statements.
  • As methods are always declared inside a class boundary hence, methods sometimes are called as member method, or member functions.
  • We call functions as methods in java, or in other words In many languages (like C and C++), the term function is used to describe a named subroutine. The name that is more commonly used in Java is method.

Note - In Java, there are only classes, nothing exists outside a class. Although you can have public methods in non-public classes, You probably don't want that since the non-public classes will have limited visibility outside of the declaring class.

Syntax -

ReturnType methodName()
// Method body 

  • A method can hava different return types as shown below -
  1. void - It means the method will not have a returning value.
  2. int -  It means the method has an integer type returning value.
  3. float -  It means the method will have a floating type returning value.
  4. double -  It means the method will have a double type returning value.
  5. Etc.

Static method -

  • We can also declare static method by putting static keyword before return type of a method.
  • A static method is invoked by - className methodName.
  • We need static method so that their is no need to create class object to call method.

static ReturnType methodName()
// Method body 

Method calling -

  • In java a method can be called using methodName with opening, and closing parentheses with a semicolon in the end.
  • A method can be called multiple times as well.
  • We will understand method calling with an example as follows -

Example -

public class T{
int i =1;
static void show() {

public static void main(String[] args) {
Output -