Get the App
SLTechnology News&Howtos  ›  Development  › 

How to define and use methods in Java

Shulou Source: shulou.com Published: 2022-06-03 11:00:21 10月04日 Update

This article mainly shows you "how to define and use methods in Java". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to define and use methods in Java".

1. Concept

The "Method" in the Java language may also be called "Function" in other languages. For some complex code logic, if you want to reuse the code and "use it at any time", you can put the code in curly braces "{}" and give it a name. When using the code, just find the name and call it.

two。 Actual combat exercise

2.1 Test the method of incoming parameters and return values

Code

MethodDemo.java

Package cn.test.logan.day04;import java.util.ArrayList;public class MethodDemo {public int num1; public int num2; / / method: syntax used to encapsulate a logical / / definition method: public returns the value type method name () {/ / logic} public int getSum () {int sum = num1 + num2; return sum } / / method with no return value, using void to denote public void say () {System.out.println ("method with no return value at this time, ");} / / method with parameter but no return value, method with the same name, but with different parameter list, overloaded public void say (String param) {System.out.println ("my input parameter is:" + param) of the method. } / / methods with multiple parameters and no return value public void say (String param1,String param2) {System.out.println ("the first parameter entered is:" + param1); System.out.println ("the second parameter entered is:" + param2);} / / methods with parameters and return values public int getDiff (int aline int b) {int diff = a-b; return diff } / / is used to sort the ArrayList public static void sortForArrayList (ArrayList list) {for (int item0)

Tags: Methods parameters code objects static members content articles logic input names multiple language learning help sorting testing complexity it doesn't matter two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft Apple macOS NVidia