Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java method and Recursion

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about Java method and recursion. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

The use of method in java what is method

To give an example in daily life, for example, our monitor at school will send a message. For example, if he wants everyone in the class to have a meeting in the so-and-so teaching building, he will send a message to everyone. Students, we have an important meeting today. We will invite you to come to the so-and-so class in the so-and-so teaching building. If the monitor wants to send a message to everyone. There are a lot of people in a class so that the monitor will be very tired to send messages. To change the way of thinking, it will be very easy for the monitor to send messages in groups. This is similar to the method in java, we define a method to implement the function you need, and you can call it whenever you want to call and implement it.

If you repeatedly implement a function in programming, it will

1. Make the program cumbersome

two。 The development is inefficient and a lot of repetitive work has been done.

3. It is not good for maintenance, and when changes are needed, all the locations where the code is used need to be modified.

4. It is not conducive to reuse.

Meaning of the method:

1. Is the organization code that can be modularized (when the scale of the contemporary code is more complex).

two。 To make sure that the code is reused, one code can be used in multiple locations.

3. Make the code easier to understand and simpler.

4. Directly call the existing method development, do not have to repeat the wheel

Definition and use of method

Define the specification:

The modifier returns the value type method name ([parameter type parameter.]) {

Method body code

[return return value]

}

Let's give an example: determine whether it is a leap year:

Public static boolean isLeapYear (int year) {if (year4 years 0 | | year%400==0) {return true;} return false;}

Realize the addition of two numbers:

Public static int add (int x, int y) {/ / realize the addition of two numbers return x + y;}

This method can be called when you need this feature, without having to write it again, reducing the redundancy of the code.

Some considerations about the method:

1. Modifier: use public static fixed collocation directly at this stage

two。 Return value type: if the method has a return value, the return value type must be the same as the returned entity type. If there is no return value, it must be written as void.

3. Method name: named after a small hump

4. Parameter list: if the method has no parameters, nothing is written in (). If there are parameters, you need to specify the parameter type, and multiple parameters are separated by commas.

5. Method body: the statement to be executed inside the method

6. In java, the method must be written in the class

7. In java, methods cannot nest definitions

8. In java, there is no method declaration to say

How to call a method and its method invocation procedure

Give an example: or the above example to judge leap years?

Public static boolean isLeapYear (int year) {if (year4 years 0 years year0 years 0 | | year%400==0) {return true;} return false;} public static void main (String [] args) {Scanner scan = new Scanner (System.in); System.out.println ("would you please enter year to determine whether it is a leap year? : > "); int year = scan.nextInt (); if (isLeapYear (year)) {/ / is a leap year System.out.print (year+" is a leap year ");} else {System.out.print (year+" is not a leap year ");}}

Let's analyze this code:

First, we need to define a year:

Call method:

We can summarize that the calling process of the method is roughly as follows:

Call method-> pass parameters-> find the method address-- > the method body that executes the called method-- > return from the end of the called method-- > go back to the main tone method and continue to execute

Note:

You can call a method only after you have defined it. And the method executes only when the method is called.

The method we define can be called repeatedly. Do what we want to do.

Take an example: calculate 1! + 2! + 3! + 4! + 5!

Although this code is simple, it can prove that we implement a function into a method, so that when we call it, the code logic is very clear, so it is suggested that we should encapsulate it into a method when we implement a function.

Formal parameters and actual parameters of the method

The formal parameter of the method in Java is equivalent to the independent variable n in the sum function, which is used to receive the value passed by the sum function when it is called. The name of the parameter can be chosen at will, which does not have any effect on the method. The parameter is just a variable that the method needs to use when it is defined to hold the value passed by the method when it is called.

For example: implement a method to exchange two integer variables

Pass the value call:

According to the above answer, it's not what we want, so why?

Let's analyze it:

Some people will still say that if I write the parameter as an and b, will he exchange the values of an and b?

The answer is no, the name of the parameter can be chosen at will and has nothing to do with the name. If it is written as an and b, it can only show that the original two people and your parameter are duplicate names, and will not change in essence.

So how on earth can we change the value of two numbers?

This is similar to the c language, in which the addresses of two numbers are passed and references are passed in java. References store the addresses of the two variables in memory, which can be changed by the address.

Because there is no so-called fetching address in java language, there is a reference type in Java, and the variable referenced by the reference type is the address stored in memory. You can actually change a value by address.

There are many reference types in java, such as classes, objects, arrays, strings, and so on.

We then use the array to exchange the values of the two numbers.

Public static void Swap (int [] array) {int tmp = array [0]; array [0] = array [1]; array [1] = tmp;} public static void main (String [] args) {int [] array = new int [] {10 int 20}; Swap (array); System.out.println (Arrays.toString (array);}

Why are the two values exchanged? Because the array is a reference type, the reference variable (in this case, array) holds the in-memory address of the elements in the array, and you can actually change these two values by address.

Method overload

Baidu encyclopedia: method overloading refers to defining multiple methods with the same name in a class, but requiring each method to have a different type of parameter or the number of parameters. When an overloaded method is called, the Java compiler can select an appropriate method by checking the parameter type and number of methods being called. Method overloading is often used to create methods that complete a set of tasks that are similar but have different types or number of parameters or different order of parameters. Java method overloading means that multiple methods can be created in a class, which can have the same name, but must have different parameters, that is, either the number of parameters is different, or the type of parameters is different. When a method is called, the specific method is determined by the different number and type of parameters passed to them, as well as the order of the parameters passed in.

If you look at the complex concepts above, you may not understand them for a while. Let me give you an example.

For example, if we want to realize the addition of numbers, we have to add two shaping numbers, two floating point numbers and three shaping numbers at the same time.

We haven't learned how to overload. It might be written like this.

Public static int addTwoInt (int a minint b) {return aint b;} public static int addThirdInt (int arech int b reint c) {return aqumb;} public static double addTwoDouble (double amerie double b) {return astatb;} public static void main (String [] args) {int a = 10; int b = 20; int c = 20; double d = 3.14 Double e = 9.89; System.out.println (addTwoInt (a, b)); System.out.println (addThirdInt (a, b, c)); System.out.println (addTwoDouble (d, e));}

For students who have learned how to overload, I really want to see this code.

Does this kind of code look tedious? every time you implement an addition, you have to give it a name. The above code needs to provide many different method names, and naming is a headache

So how much does it change when we use method overloading next?

We all use the same name and will not report errors in idea because overloading of methods is supported in the Java language.

So, in Java, if multiple methods have the same name and different parameter lists, they are said to be overloaded

According to these three codes, we can summarize the rules of method overloading.

First: the method name is the same

Second, the return value is not required

Third: the parameter list of the method name is different (including the return type of the parameter, the order of the parameter, the number of parameters)

Method signature

Now that there is a way to overload, how does java support overloading internally? Then let's talk about the method signature.

The method signature is the final name of the method after being compiled and modified by the compiler. Specific method: method full path name + parameter list + return value type, constitute the complete name of the method.

We find the .class file that generated the code and then right-click to open powershell

Enter a javap-v + file name

After you enter, you can see the assembly code of the java code, and according to the assembly code, you can see the signature of the method.

Now that we have defined a method with the same name, how does the compiler know which method we want to call? Yes, this is why the method signature works. Every time you define a method to compile and generate a class file, it will generate a method signature, and the compiler will identify it according to the signature of each method. For example, if you want to calculate the sum of two double types, he will directly find this signature of DD and will not match the other signatures.

Recursion

Recursive definition is a way of definition used in mathematical logic and computer science, using the defined object itself to define it (in short, the definition of self-replication). Recursive definition (recursive definition), also known as inductive definition, is a substantive definition that uses recursive methods to define a concept.

Generally speaking, when we encounter a problem, the solution of each step of the problem is the same, we can decompose the big problem into multiple sub-problems, and eventually the problem will be solved.

There are two necessary conditions for implementing recursion:

First: the sub-problem must be solved in the same way as the original problem.

Second, there must be a judgment condition to prevent stack overflow caused by too deep recursion.

Let's take a classic recursive example: finding the factorial of N

We can think about the reasoning according to the above figure: first, he accords with the solution of the original problem and the solution of the sub-problem is consistent with the judgment condition (the judgment condition is if the solution of the original problem is 1! = 1). This is recursive from 5! Is broken down into 5'4! Oh, four, three! .

Such a problem can be easily solved.

Public static int factor (int n) {if (factor (5)) {return 1;} return n * factor (NMMI 1);} public static void main (String [] args) {System.out.println (factor (5));}

Recursive exercise

Print each bit of a number in order (for example, 1234 prints out 1234).

How do we think about this question?

First of all, to get a number of each bit must be divided by 10 and module 10 loop to know that the number is 0

Then we can decompose 1234 in this way.

Public static void printEveryNum (int num) {if (num)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report