In this section will discus about What is Method and How to create Methods in Java. A method in Java is a set of statements that are grouped together to perform various actions. For example, when a System.out.println()
method is called, the system actually executes several statements in order to display messages on the console.
Next, learn how to create your own methods with or without return values, call methods with or without parameters, and apply method abstraction in programming.
Let's have a look at the syntax of the method −
|
In the syntax above,
public static
− Rhetoricint
− the type of the return valuemethod Name
− the name of the methoda, b
− Formal parametersint a, int b
− parameter listA method definition consists of a method header and a method body. The same is shown in the following syntax −
|
modifier
- It defines the access type of the method, it may be: public
, private
, protected
or not specified.return Type
- A method can return a value.name Of Method
- This is the method name, and the method signature consists of the method name and the parameter list.Parameter List
- The parameter list, which is the method's type, order and number of parameters. These are optional and methods may contain zero arguments.method body
- The method body defines what the method does to the statement.example
The method is defined in the following code min()
. This method takes two int
parameters of type: num1
and num2
, and returns the maximum value between the two -
|
A method can be used by calling a method. There are two ways to call a method, that is, the method returns a value or does not return any value.
The process of method invocation is simple. When a program calls a method, program control is transferred to the called method. This called method then returns control to the caller on two conditions, namely −
return
statement is executed.}
).A call to the returned void
method -
|
|
|
Execute the above sample code and get the following results:
Min number = 111
void
The keyword allows the creation of methods that do not return a value. In the example below there is void
a method with a return value of methodRankPoints
, which does not return any value. Invoking a void
method must be a statement i.e. methodRankPoints(245.67);
it is a Java statement ending with a semicolon as shown in the following example −
|
Rank:A1
Parameters need to be passed when passing them by value. They should be in the same order as the parameters in the method specification. Parameters can be passed by value or reference.
Passing parameters by value is calling a method with parameters. By doing this the parameter value will be passed to the parameter.
example
The following program shows an example of passing parameters by value. Even after the method call, the value of the parameter remains the same.
|
Execute the above sample code and get the following results:
|
When a class has two or more methods with the same name but different parameters, it is called method overloading. It's not the same as rewriting. In an override, methods have the same method name, type, number of parameters, etc.
In the example discussed earlier for finding the smallest number of an integer type, suppose you wanted to find double
the smallest number of two types. The concept of overloading can be introduced to create two or more methods with the same name but different parameters.
Refer to the following sample code −
|
Execute the above sample code and get the following results:
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes programs readable. Here, two methods are given by the same name but have different parameter types. The result is to find the minimum number of int
types and types.double
Some times it is desirable to pass some information to a program when it is run. It does so by passing command-line arguments to main()
.
Command-line arguments are information that directly follows the program name on the command line when executed. Accessing command line arguments in a Java program is very simple. They are stored as strings in main()
the String
typed array passed to .
example
The following program displays all the command line arguments passed to the program −
public class CommandLine {
public static void main(String args[]) {
for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
Execute this procedure using −
C:/> java CommandLine this is a command line 200 -100
Then the following result will be obtained:
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
this
is a keyword in Java used as a reference to the current class object, within an instance method or constructor. Use it to refer to members of a class such as constructors, variables and methods.
Note -
this
The keyword is only used in instance methods or constructors.
Usually, this
keywords are used for −
Instance variables are distinguished from local variables if they have the same name within a constructor or method.
class Student {
private int age;
Student(int age) {
this.age = age;
}
}
Invoking a type of constructor (either a parameterized constructor or a default) from another method in the class is called an explicit constructor call.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Following is this
an example of accessing class members using keywords −
public class ThisExample {
int num = 10;
ThisExample() {
System.out.println("This is an example program on keyword this");
}
ThisExample(int num) {
this();
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to Yiibai");
}
public void print() {
int num = 20;
System.out.println("value of local variable num is : "+num);
System.out.println("value of instance variable num is : "+this.num);
this.greet();
}
public static void main(String[] args) {
ThisExample obj1 = new ThisExample();
obj1.print();
ThisExample obj2 = new ThisExample(30);
obj2.print();
}
}
Execute the above sample code and get the following result −
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Yiibai
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Yiibai
JDK 1.5 allows a variable number of parameters of the same type to be passed to a method. The parameters in the method are declared as follows −
type Name... parameter Name
In a method declaration, specify the type followed by an ellipsis ( ...
). Only one variable-length parameter can be specified in a method, and this parameter must be the last parameter.
public class VarargsDemo {
public static void main(String args[]) {
printMax(314, 321, 213, 212, 356.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println( result);
}
}
Execute the above sample code and get the following result −
356.5
3.0
The finalize() method is called before the object is finally destroyed by the garbage collector, and it can be used to ensure that the object is fully finalized. For example, you can use finalize()
to ensure that open files owned by this object are closed.
To add a finalizer to a class, just define a finalize()
method. It calls this method whenever a Java method wants to recycle an object of that class.
In the finalize()
method, you will specify the actions that must be performed before the object is destroyed. finalize()
A method has this general form -
protected void finalize( ) {
// finalization code here
}