Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Methods

Java Methods

In the previous chapters we have frequently used System.out.println(), so what is it?

The usage of this statement is to call the method println() of the standard output object out in the system class System.

So what is a method?

A Java method is a collection of statements that execute a single function together.

Advantages of methods

Method naming rules


Method definition

Generally, defining a method includes the following syntax:

Modifier Return value type Method name

(

Parameter type Parameter name

)

{

... method body ...

return

return value;

}

A method consists of a method header and a method body. The following are all parts of a method:

For example:

public

static

int

age

(

int

birthday

)

{

...

}

A method can have multiple parameters:

static

float

interest

(

float

principal

,

int

year

)

{

...

}

Note: In some other languages, methods refer to procedures and functions. A method that returns a non-void value is called a function; a method that returns void is called a procedure.

Example

The following method contains two parameters, num1 and num2, and returns the maximum of these two parameters.

/*

*/

public

static

int

max

(

int

num1

,

int

num2

)

{

int

result

;

if

(

num1

num2

)

result

=

num1

;

else

result

=

num2

;

return

result

;

}

A more concise way (ternary operator):

public

static

int

max

(

int

num1

,

int

num2

)

{

return

num1

num2

?

num1

:

num2

;

}


Method Call

Java supports two ways of calling methods, chosen based on whether the method returns a value.

When a program calls a method, control of the program is transferred to the called method. Control is returned to the program when the called method's return statement is executed or its closing brace is reached.

When a method returns a value, the method call is usually treated as a value. For example:

int

larger

=

max

(

30

,

40

)

;

If a method returns void, the method call must be a statement. For example, the method println returns void. The following call is a statement:

System

.

out

.

println

(

"

Welcome to Runoob Tutorial!

"

)

;

Example

The following example demonstrates how to define a method and how to call it:

TestMax.java file code:

public

class

TestMax

{

/*

*/

public

static

void

main

(

String

[

]

args

)

{

int

i

=

5

;

int

j

=

2

;

int

k

=

max

(

i

,

j

)

;

System

.

out

.

println

(

i

"

and

"

j

"

Comparison, the maximum value is:

"

k

)

;

}

/*

*/

public

static

int

max

(

int

num1

,

int

num2

)

{

int

result

;

if

(

num1

num2

)

result

=

num1

;

else

result

=

num2

;

return

result

;

}

}

The compilation and execution results of the above example are as follows:


5 和 2 比较,最大值是:5

This program contains the main method and the max method. The main method is called by the JVM; otherwise, the main method is no different from other methods.

The header of the main method is fixed, as shown in the example: it has the modifiers public and static, returns a void value, the method name is main, and it takes a String[] parameter. String[] indicates that the parameter is a string array.


void keyword

This section explains how to declare and call a void method.

The following example declares a method named printGrade and calls it to print the given score.

Example

TestVoidMethod.java file code:

public

class

TestVoidMethod

{

public

static

void

main

(

String

[

]

args

)

{

printGrade

(

78

.5

)

;

}

public

static

void

printGrade

(

double

score

)

{

if

(

score

=

90

.0

)

{

System

.

out

.

println

(

'

A

'

)

;

}

else

if

(

score

=

80

.0

)

{

System

.

out

.

println

(

'

B

'

)

;

}

else

if

(

score

=

70

.0

)

{

System

.

out

.

println

(

'

C

'

)

;

}

else

if

(

score

=

60

.0

)

{

System

.

out

.

println

(

'

D

'

)

;

}

else

{

System

.

out

.

println

(

'

F

'

)

;

}

}

}

The compilation and execution results of the above example are as follows:


C

Here the printGrade method is a void-type method; it does not return a value.

A call to a void method must be a statement. Therefore, it is called as a statement on the third line of the main method, just like any statement ending with a semicolon.


Passing parameters by value

When calling a method, you must provide arguments in the order specified by the parameter list.

For example, the following method prints a message n times in a row:

TestVoidMethod.java file code:

public

static

void

nPrintln

(

String

message

,

int

n

)

{

for

(

int

i

=

0

;

i

<

n

;

i

++

)

{

System

.

out

.

println

(

message

)

;

}

}

Example

The following example demonstrates the effect of pass-by-value.

This program creates a method that swaps two variables.

TestPassByValue.java file code:

public

class

TestPassByValue

{

public

static

void

main

(

String

[

]

args

)

{

int

num1

=

1

;

int

num2

=

2

;

System

.

out

.

println

(

"

Value of num1 before swap:

"

num1

"

, value of num2:

"

num2

)

;

//

Call the swap method

swap

(

num1

,

num2

)

;

System

.

out

.

println

(

"

Value of num1 after swap:

"

num1

"

, value of num2:

"

num2

)

;

}

/*

*/

public

static

void

swap

(

int

n1

,

int

n2

)

{

System

.

out

.

println

(

"

\t

Entering the swap method

"

)

;

System

.

out

.

println

(

"

\t

\t

Value of n1 before swap:

"

n1

"

, value of n2:

"

n2

)

;

//

Swap the values of n1 and n2

int

temp

=

n1

;

n1

=

n2

;

n2

=

temp

;

System

.

out

.

println

(

"

\t

\t

Value of n1 after swap:

"

n1

"

, value of n2:

"

n2

)

;

}

}

The compilation and execution results of the above example are as follows:


交换前 num1 的值为:1 ,num2 的值为:2
    进入 swap 方法
        交换前 n1 的值为:1,n2 的值:2
        交换后 n1 的值为 2,n2 的值:1
交换后 num1 的值为:1 ,num2 的值为:2

Two arguments are passed to call the swap method. Interestingly, after the method is called, the values of the arguments are not changed.


Method overloading

The max method used above only applies to int data. But what if you want the maximum of two floating-point values?

The solution is to create another method with the same name but different parameters, as shown in the following code:

public

static

double

max

(

double

num1

,

double

num2

)

{

if

(

num1

num2

)

return

num1

;

else

return

num2

;

}

If you pass int arguments when calling the max method, the max method with int parameters is called;

if you pass double arguments, the max method with double type is called; this is called method overloading;

that is, two methods in a class have the same name but different parameter lists.

The Java compiler determines which method should be called based on the method signature.

Method overloading makes programs clearer and more readable. Methods that perform closely related tasks should use the same name.

Overloaded methods must have different parameter lists. You cannot overload methods based solely on differences in modifiers or return types.


Variable scope

The scope of a variable is the part of the program where the variable can be referenced.

Variables defined inside a method are called local variables.

The scope of a local variable starts from its declaration and ends at the closing brace of the block that contains it.

Local variables must be declared before they can be used.

A method's parameters are in scope throughout the entire method. A parameter is essentially a local variable.

Variables declared in the initialization part of a for loop are in scope for the entire loop.

However, a variable declared inside the loop body is in scope from its declaration to the end of the loop body. It includes variable declarations as shown below:

You can declare a local variable with the same name multiple times in different non-nested blocks within a method, but you cannot declare a local variable twice within a nested block.

Using command-line arguments

Sometimes you want to pass a message to a program when running it. This is done by passing command-line arguments to the main() function.

Command-line arguments are the information that follows the program name immediately when the program is executed.

Example

The following program prints all command-line arguments:

CommandLine.java file code:

public

class

CommandLine

{

public

static

void

main

(

String

[

]

args

)

{

for

(

int

i

=

0

;

i

<

args

.

length

;

i

++

)

{

System

.

out

.

println

(

"

args[

"

i

"

]:

"

args

[

i

]

)

;

}

}

}

Run this program as follows:


$ javac CommandLine.java 
$ java CommandLine this is a command line 200 -100
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Constructor

A constructor is a special method used to create objects of a class. When an object is created using the new keyword, the constructor is called automatically to initialize the object's properties.

Constructor characteristics:

Whether or not you define a constructor yourself, all classes have a constructor, because Java automatically provides a default constructor whose access modifier is the same as the class's access modifier (if the class is public, the constructor is also public; if the class is changed to protected, the constructor is also changed to protected).

Once you define your own constructor, the default constructor becomes invalid.

Example

The following is an example using a constructor:

//

A simple constructor

class

MyClass

{

int

x

;

//

The following is a constructor

MyClass

(

int

i

)

{

x

=

i

;

}

}

You can call a constructor like the following to initialize an object:

ConsDemo.java file code:

public

class

ConsDemo

{

public

static

void

main

(

String

[

]

args

)

{

MyClass

t1

=

new

MyClass

(

10

)

;

MyClass

t2

=

new

MyClass

(

20

)

;

System

.

out

.

println

(

t1

.

x

"

"

t2

.

x

)

;

}

}

The running result is as follows:


10 20

For more content, refer to the next chapter:Java Constructor.

Variable arguments (varargs)

Starting with JDK 1.5, Java supports passing a variable number of arguments of the same type to a method.

A method's variable arguments are declared as follows:

typeName

...

parameterName

In a method declaration, add an ellipsis (...) after the specified parameter type.

A method can specify only one variable argument, and it must be the last parameter of the method. Any ordinary parameters must be declared before it.

Example

VarargsDemo.java file code:

public

class

VarargsDemo

{

public

static

void

main

(

String

[

]

args

)

{

//

Calling a method with variable arguments

printMax

(

34

,

3

,

3

,

2

,

56

.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

(

"

The max value is

"

result

)

;

}

}

The compilation and execution results of the above example are as follows:


The max value is 56.5
The max value is 3.0

finalize() method

The finalize method was marked deprecated in Java 9 and will be removed in future Java versions. It is recommended to use try-with-resources or java.lang.ref.Cleaner to manage resources.

Java allows defining such a method, which is called before an object is destructed (reclaimed) by the garbage collector; this method is called finalize(), and it is used to clean up reclaimed objects.

For example, you can use finalize() to ensure that a file opened by an object is closed.

In the finalize() method, you must specify the operations to be performed when the object is destroyed.

The general format of finalize() is:

protected

void

finalize

(

)

{

//

Finalization code here

}

The protected keyword is a qualifier that ensures the finalize() method cannot be called by code outside the class.

Of course, Java's memory reclamation can be done automatically by the JVM. If you do it manually, you can use the method above.

Example

FinalizationDemo.java file code:

public

class

FinalizationDemo

{

public

static

void

main

(

String

[

]

args

)

{

Cake

c1

=

new

Cake

(

1

)

;

Cake

c2

=

new

Cake

(

2

)

;

Cake

c3

=

new

Cake

(

3

)

;

c2

=

c3

=

null

;

System

.

gc

(

)

;

//

Call the Java garbage collector

}

}

class

Cake

extends

Object

{

private

int

id

;

public

Cake

(

int

id

)

{

this

.

id

=

id

;

System

.

out

.

println

(

"

Cake Object

"

id

"

is created

"

)

;

}

protected

void

finalize

(

)

throws

java

.

lang

.

Throwable

{

super

.

finalize

(

)

;

System

.

out

.

println

(

"

Cake Object

"

id

"

is disposed

"

)

;

}

}

After running the above code, the output is as follows:


$ javac FinalizationDemo.java 
$ java FinalizationDemo
Cake Object 1is created
Cake Object 2is created
Cake Object 3is created
Cake Object 3is disposed
Cake Object 2is disposed

**Alternative:** It is recommended to use the AutoCloseable interface, combined with the try-with-resources statement, to automatically close resources. For example:


try (Resource res = new Resource()) {
    // Use resources
} catch (Exception e) {
    e.printStackTrace();
}