A method is a block of instructions(one or more line of codes) given in { } inside a class. This block is referred by a name which is basically the method name. The name of method is used to call(invoke) that method within or outside a class. Once a method is called, the code given inside that method is executed. After execution a method may or may not return a value. The most basic or minimal Syntax of declaring a method is :
// Method without parameter
Return_Type methodName() {// one or more line of code.
return
some_value; }// Method with parameter
Return_Type methodName(DataType param1, DataType param2 ...) {// one or more line of code.
return
some_value; }
A method must have a return type which basically tells what type of value this method returns. The Return_Type of a method can be
primitive or non-primitive data type. If a method doesn't return a value, it's
return type must be void
or in other way if the return type of a method is void
, it means that method doesn't return any value.
The name of the method is given by the
programmer. As per the convention the method name should be in small letters while in multiWord method name, the first letter of any subsequent word should be in capital letter. For example method
names like add(), calculateArea(), getName()
etc are some examples of this convention.
After method name, it's the parameters given inside () which are basically variables. Parameters are optional which means a method may or may not have parameters. You can access these parameters within
the method only, not outside the method. The data type of parameters can be primitive or non-primitive. After parameters it's method body given inside { }
.
Everything given inside { } after method name are the part of that method.
Let's see some examples of method declaration.
int
add(int
num1,int
num2) {// one or more line of code.
return
value;// returns integer value.
}void
calculateArea() {// one or more line of code.
}
Can I give any name to method ?
Yes you can given any name by following the identifier naming convention but giving a meaningful name is a good programming style.
The name should itself suggest that what this method does.
For example method names like xyz(), method123()
are valid names but not meaningful names while names like add(), calculateArea(), getColor()
are meaningful names.
Built-in vs. User defined methods
Methods that are defined inside the classes included in java software are known as built-in methods. For example println()
method, String
class methods like
charAt(), toLowercase(), trim()
etc are built-in methods.
The methods that programmers defined inside their classes is known as user defined methods. It's programmer who gives the name to his method and code inside that method.
Can't I include all code or logic inside a single method ? Why I should create different methods ?
Yes you can include all logics or code inside a single method but that's not a good programming style. A good programmer always creates different methods for different tasks which makes your program more readable and modular.
Parameter vs Argument
Parameters are the variables declared inside the ()
after the method name. These parameters can be accessed inside the method only. For example in method declaration
add(
, variables int
num1, int num2
)num1
and num2
are parameters. Arguments are the values that
are passed to method while calling the method. For example in a method call add(20,30)
, 20 and 30 are arguments.
Static and Non Static Method
A method declared with static
keyword is known as static method. Static method belongs to class not object which means you don't need to create object to access such
methods. You can access static methods with class name itself. Methods defined without static
keyword is known as non static
method, also known as instance method. You need object or instance of the class to access such methods. For example in below program calculateArea()
is a static method while
add(), firstMethod(), secondMethod()
are non static methods.
Static method can access only static
variables inside it's body while non static method can access both static
and non static variables.
We will discuss more about this in later tutorial.
Java Method Program
class
MethodDemo {public static void
main(String [] args) { MethodDemo md =new
MethodDemo();int
sum = md.add(20,30);// calling add() method
System.out.println("sum = "
+sum); md.firstMethod();// calling firstMethod() using object
MethodDemo.calculateArea(100,50);// calling calculateArea method using className
}int
add(int
num1,int
num2) {int
sum = num1 + num2;return
sum; }void
firstMethod() { System.out.println("Inside first method"
); secondMethod();// calling secondMethod()
System.out.println("After calling second method"
); }void
secondMethod() { System.out.println("Inside second method"
); }static
void calculateArea(int
length,int
width) {int
area = length*width; System.out.println("Area = "
+area); } }
Output:
sum = 50
Inside first method
Inside second method
After calling second method
Area = 5000
As you can see static
method calculateArea()
is called using class name MethodDemo
. You can call static
method using object as well, but that's not a good practice, since
static
methods belongs to class not object. You should always prefer to call static
methods using class name.
What is called method and calling method ?
A method that calls a given method is known as calling method while the method that is being called is known as called method. For example in above program, main()
is the
calling method for called methods firstMethod()
and calculateArea()
.
Can I pass object inside method calling ?
Yes you can pass objects as well inside the method. Any changes made in that object in called method will be reflected in calling method as well.
How method execution happens in Java ?
As soon as a method is called, the execution of that method get's started. Once the execution of method completed or any return
keyword encountered, the execution control
comes back to the position from where it was called. Once a method is called, java creates a new stack inside stack memory where all local variables of that method are initialized.
For example in above program once line
executed, the execution
of int
sum = md.add(20,30);add
method get's started. As soon as the return
statement in add
method is executed, the execution control again comes back
to the line
where the value returned by int
sum = md.add(20,30);add
method is assigned in variable sum
.
What is method signature ?
The name and the parameters of a method in a method declaration is referred as method signature. Other components like access modifiers, return type etc are not the part of method signature.
For example method signature of add
method in above program is add(
.int
num1, int
num2)
You can define multiple methods with same name having different parameter lists. Java differentiates such methods on the basis of the number of parameters in the list and their types. This is known as method overloading. We will discuss method overloading in later tutorials.
The syntax of declaring a method given in this tutorial is the minimal one which is required. Apart from this there are couple of more keywords as given below that can be used with method declaration. We will discuss these keywords with methods in later tutorials.
- An access modifier(
public, protected, private
) can also be used with method declaration. Access modifiers decides the visibility/accessibility of method within or outside the class. For example aprivate
method can only be accessed within the class whilepublic
method can be accessed from outside the class as well. final
keyword can also be used with method declaration.final
method can not be overridden.abstract
keyword can also be used with method declaration. The implementation or definition of abstract method is defined by sub class.- A method can also declare an exception using
throws
keyword.
- Accessing a method means calling that method.
- Functions in other programming language are equivalent to methods in java programming.
- There should be only one main method having argument type as
String []
in a class. - When you pass an object inside a method, the reference of that object is passed to the method.
- Method that returns a boolean value, can be called inside a conditional statement as well like
if(isValid()), if(isEmpty())
etc.