Notes for Java functions

Source: Internet
Author: User

In Java, a function is a method. That is, the way to implement a function.

Format of the function

Modifier returns a value type function name (parameter type parameter) {

logical processing;

return processing results; The return keyword is used to end the function and returns the processing result to the caller. The void type can omit return, but when compiled into a. class file, there is a return in the code.

}

How do you define a function?

When defining a function, make two points clear:

1. What is the result of this feature?

2. What are the parameters that this function needs to pass?

Common misunderstanding of new handwriting function

Error code example

Class MethodDemo2

{
public static void Main (String [] args) {
Add (4,5);
}

public static void Add (int a, int b) {
System.out.println (A + B);
Return
}
}

The above code, although the result is correct, is not logical. Because the Add (int a, int b) function is only used for addition operations, there should be no printing operations.

The right approach should be a function that corresponds to a function.

Class MethodDemo2 {
public static void Main (String [] args) {
int sum = Add (4,5);
SYSTEM.OUT.PRINTLN (sum); The printing function should be a standalone method
}

public static int Add (int a, int b) {//The arithmetic function is only responsible for the operation
return a + B;
}
}

Suggestions

A function should not exceed 20 lines, if the logic is more, you can split multiple functions, called by the function name. The purpose is to facilitate debugging.

Overloading of functions

A function with the same name in a class is called a function overload (overload), as long as the number of arguments is different from the parameter type. Is independent of the return value type.

Notes for Java functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.