Chapter IV Functions
What we do in life is to have an idea of doing something in our mind instead of directly planning what happens in the first second and what happens in the second after what happens in the first second. It is clear that this is neither meaningful nor cumbersome.So I think the use of functions is similar.The main main function in the program is equivalent to the "brain". Calling a function is to generate the idea to do specific actions, and the specific completion of actions depends on the function implementation.
So what are the advantages and disadvantages?Answers will be given below
Advantages: reduced code size for main function, high readability, easy to modify, stack memory optimization, code reuse
Disadvantages: stack memory is exploited when called, which reduces efficiency
Definition of Function
Code snippets encapsulated to solve duplicate problems with independent functional implementations
Format of function (component)
Access rights
What this means is the scope (inside and outside) of the function
public,private,protected
(Default not written)
Function Types
Static static function, abstract abstract function, native local function, synchronized synchronized function
(Member functions are not written by default)
Function Name [Identifier]
Ps: Reference identifier naming rules and naming conventions.
List of parameters
Receive specific types or compatible data from external incoming functions
Functional Body
Code blocks that implement stand-alone functionality
Return value (type-sensitive)
Function achieves results using return.The return type is consistent or compatible.
Classification of functions
With/without parameters, with/without return values
Function parameters
Actual parameters (arguments)
The data (constants, variables) passed to a function when it is called are called arguments
Formal parameters (formal parameters)
When defining a function, the data in the parameter list is called a parameter
Deliveries are addresses
I. Address of Constant in Constant Pool
II. Address of object in heap
Let's take a look at the results of the following tests:
public class Text{ public static void main(String[] args){ int[] a = new int[5]; show(a); //Print Array a Initial Value f(a); //Call function f() show(a); //Print a array again } public static void f(int[] b){ //Function f() for(int i=0;i < b.length;i++) b[i]=1; } public static void show(int[] c){ //Print function for(int i=0;i<c.length;i++) System.out.print(c[i]); System.oout.println(); } }
The initial value of the array defaults to 0.Arrays are also objects in Java, and the array passed by the calling function f(a) is actually the first address of the array a of objects in heap memory.So the value of array a changes after calling the function.
Variable Scope,
Local variables but variables created in a function are called local variables The scope of local variables is only in the current function (formal parameters must be local variables).
Function Stack
(Function runs based on stack memory)
The stack is a FIFO container structure, the function is called into the stack (the main function is absolutely the first to go into the stack), and the function ends the stack.
Function overloading
Functions with the same name that occur in the same class are distinguished only by the type, number, and order of the parameters
Call the parameter to find out if there is a function defined by an exact parameter; if there is no more compatible function; if there is no error, the reference is ambiguous
Recursive calls to functions
Functions call themselves.Use function runs based on stack memory, FIFO
Recursion
Recursion is actually a way of realizing divide-and-conquer (a way of thinking)
Divide-and-conquer is an algorithmic idea. The main problem solved by divide-and-conquer is to divide a large problem into several small problems to solve, and finally merge the solutions of each small problem.In fact, divide-and-conquer is a violent solution (exhaustion) and an algorithm for searching for the best answer
Complete the condition first!
Recursion after recursion;
The previous paragraph is about getting bigger and smaller
If the problem can no longer be reduced to a smaller size, the current problem will be addressed
Back Segment Back Up (Some problems don't need to be returned)
Non-recursive
import java.util.Scanner; public class Text{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.print("Enter:"); int n=sc.nextInt(); //Keyboard input n value System.out.println(fibo(n)); //Call a normal function to print the value of item n } public static int fibo(int n){ //Normal function, returns the value of the nth term int a=1; int b=1; int num=1; for(int i=3;i<=n;i++){ num=a + b; a=b; b=num; } return num; } }
Recursive method
import java.util.Scanner; public class Text{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.print("Enter:"); int n=sc.nextInt(); //Keyboard input n value System.out.println(fibo(n)); //Call a recursive function to print the value of item n } public static int fibo(int n){ if(n==1||n==2) //Conditions for ending recursion return 1; return fibo(n-1)+fibo(n-2); //Recursive implementation } }
Common Functions
Functions in Math Class
Math.E;Math.PI;Math.abs();Math.pow();Math.sqrt();Math.random();......
String class and its functions
The string is Java The special class in is widely used in Java programming, just like the basic data type in general.Java does not have a built-in string type, but instead provides a String class in the standard Java class library to create and manipulate strings.
The easiest way to define a string in Java is to enclose it in double quotes.This double-quoted string of characters is actually a String object, such as the string "Java" that becomes a String object after compilation.So you can also define strings by creating instances of the String class.
Define directly:
String str = "Java"; //or String str; str = "Java";
Class definitions:
String str1 = new String("Java"); String str2 = new String(str1);
Common functions in a class:
Query correlation
char charAt(int index)
int indexOf(int ch)
int lastIndexOf(int ch)
int length()
substring(int beginIndex, int endIndex)
Judging correlation
boolean contains(String s)
boolean endsWith(String s)
boolean startsWith(String prefix)
int compareTo(String anotherString)
boolean equals(String anotherString)
boolean equalsIgnoreCase(String anotherString)
boolean isEmpty()Modifications to strings are often new strings that assign values to the modified content and return a new string
String replace(char oldChar, char newChar)
String toUpperCase()
String toLowerCase()
String trim()
Note:
I. A modification to a string is never a modification to itself; the string itself is immutable
II. Regardless of the form used to create a string, once a string object is created, its value cannot be changed, but it can be changed by revaluing other variables.
III. The method of obtaining length distinguishes between strings - > str.length();
Array -->lilst.length;
Practice program
import java.util.Scanner; public class Home04{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.print("Enter:"); String password=sc.nextLine(); //Input password //Call the judgment function and print the results if(password.length()>=8&&only(password)&&atLeast(password)){ System.out.println("Valid Password."); }else{ System.out.println("Invalid Password."); } } public static boolean only(String p){ //Determine if only numbers and letters exist for(int i=0;i<p.length();i++){ if((p.charAt(i)>=48&&p.charAt(i)<=57)||(p.charAt(i)>=65&&p.charAt(i)<=90)||(p.charAt(i)>=97&&p.charAt(i)<=122)){ }else{ return false; } } return true; } public static boolean atLeast(String p){ //Determine if the number is greater than two int t=0; for(int i=0;i<p.length();i++){ if(p.charAt(i)>=48&&p.charAt(i)<=57) t++; } return t>=2?true:false; } }
import java.util.Scanner; public class Home11{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.print("Enter first:"); String str1=sc.nextLine(); //Enter the first string System.out.print("Enter second:"); String str2=sc.nextLine(); //Enter the second string showBig(str1,str2); //Call function to find longest prefix } public static void showBig(String s1,String s2){ //Find the longest prefix and print for(int i=0;i<(s1.length()<s2.length()?s1.length():s2.length());i++){ if(s1.charAt(i)!=s2.charAt(i)){ if(i==0) System.out.println("No one!"); break; }else{ System.out.print(s1.charAt(i)); } } System.out.println(); } }
import java.util.Scanner; public class Home12{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.print("Enter:"); String num=sc.nextLine(); //Enter a string that represents a hexadecimal number //Call the conversion function to print the results System.out.println(hexToDecimal(num.toUpperCase())); } public static int hexToDecimal(String str){ //Converting hexadecimal numbers to decimal numbers int number=0; for(int i=0;i<str.length();i++){ if(str.charAt(i)>=48&&str.charAt(i)<=57){ number=number * 16 + (str.charAt(i) - 48); }else if(str.charAt(i)>=65&&str.charAt(i)<=70){ number=number * 16 + (str.charAt(i) - 65 + 10); } } return number; } }