The program decomposition
A method is a sequence of statements grouped together to perform an operation. In Java, a method is always located inside a class. The relation between methods and classes will be learned further. In this topic, all methods will be located in the same class which contains the main
method.
In this topic, you will learn how to define new methods. It is assumed you've already known how to invoke existing methods.
The base syntax of methods
In general case, a method has the following six components:
- a name;
- a set of modifiers (
public
,static
, etc) - a type of the return value;
- a list of parameters (as well known as formal parameters) in parenthesis
()
; - a list of exceptions;
- a body containing statements to perform the operation.
Some of these components are always required and others are optional.
Now, we will focus on 1, 3, 4 and 6 components. Modifiers will be learned in topics, related to object-oriented programming.
Defining a simple method
Here is an example of a simple method that calculates the sum of two given numbers:
public static int sum(int a, int b) {
return a + b;
}
The sum
is a typical method written in Java. It returns the sum of two its parameters. The parameters are written in the parenthesis "(...)"
. To return the integer result the keyword return
is written.
In general case, a returning value and parameters can have any type, including non-primitive types.
public
and static
.Signatures
The combination of the name of a method and its parameters is called the signature. It doesn't include:
- the returning type
- modifiers
- names of parameters
sum
has the signature sum(int, int)
.sum(double, double)
min(long, long, long)
getValue()
Naming methods
- identifiers are case-sensitive;
- an identifier can include Unicode letters, digits, and two special characters (
$
,_
); - an identifier can't start with a digit;
- identifiers must not be a keyword.
sum
getValue
calculateNumberOfOranges
findUserByName
printArray
The listed methods satisfy the convention.
The type of a returning value and parameters.
A method can return a single value or nothing. To declare a method returns nothing you should write the special keyword void as the type of a result value.
The following method prints the sum of two given numbers and returns no value.
public static void printSum(int a, int b) {
System.out.println(a + b);
}
A method can take one or multiple parameters of the same or different types. Also, it's possible to declare a method without any parameters, but "()" are still required.
/**
* The method has an int parameter
*/
public static void method1(int a) {
// do something
}
/**
* The method has long and double parameters
*/
public static void method2(long a, double b) {
// do something
}
/**
* The method has no any parameters and returns a value
*/
public static int method3() {
return 3;
}
When you call a method with a value of a primitive type then a copy of the value is created. Inside a method, you can process this copy. If you change it, the passed argument is not changed.
public static void main(String[] args) {
int val = 100; // 100
change(val); // try to change val
System.out.println(val); // it prints "100", because the method changed a copy of the val
}
/**
* The method changes a given value
*/
public static void change(int val) {
val = 400; // now, the copy is 400
}
Method's body
In a method's body, you can write any statements including the conditional statement, any loops, invoking methods and declaring local variables. The declared variables are visible only in this method.
If a method returns a value, the method's body must contain the return
keyword. Moreover, a method may have multiple returns. But each state can return only a single value.
Let's see an example. The following method performs the integer division on a given value the specified number of times.
public static int divideBy2(int number, int times) {
if (times <= 0) {
return number;
}
for (int i = 0; i < times; i++) {
number /= 2;
}
return number;
}
The method divideBy2
takes two integers and returns another integer value. If the specified parameter times
is less than or equal to zero, the result is the given number
, otherwise, the method performs the integer division by two in a loop.
If a method doesn't return a value (it has the keyword void
), the method body may contain the return
keyword without returning value. It allows finishing the method ahead of schedule, for example, depending on a condition.
For example, the following method prints its arguments if given numbers are positive, otherwise, it performs the return statement.
public static void returnNothingOrPrintNumbers(int a, int b) {
if (a <= 0 || b <= 0) {
return;
}
System.out.println(a + " " + b);
}