Believe that most beginners of Java will have doubts, what is the difference between reference and pointer?
Let's take a look at the Exchange function in the C language
1#include"stdio.h"2 voidSwapint*a,int*b)3 {4 inttemp=*A;5*a=*b;6*b=temp;7 }8 Main ()9 {Ten intA=1, b=2; OneSwap (&a,&b); Aprintf"%d%d", A, b); -}
It's simple, just pass an address with your pointer, but what about a pointer in Java?
You can only create object implementations or use arrays without pointers.
1 Public classSwaptest {2 3 Public intA;4 Public intb;5 6 Public Static voidMain (string[] args) {7 8Swaptest s =Newswaptest ();9S.a=1;Tens.b=2; One Change (s); ASystem.out.println (s.a+ "" +s.b); - } - Public Static voidChange (Swaptest i) { the inttemp=I.A; -I.a=I.B; -i.b=temp; - } +}
See here maybe someone would say that an Integer is also a reference type why can't we just use it to pass it? We can look at it.
1 Public classSwaptest {2 3 4 Public Static voidMain (string[] args) {5 6 7Integer a=1,b=2;8 Change (A, b);9System.out.println (+ "+" +b);Ten } One Public Static voidChange (Integer A,integer b) { AInteger temp=A; -A=b; -b=temp; the } -}
The output is still 1 2.
What is this for?
Let's look at one more example.
1 Public classSwaptest {2 3 4 Public Static voidMain (string[] args) {5 6 7Integer a=1, B;8b=A;9b=2;Ten OneSystem.out.println (+ "+" +b); ASystem.out.println (a==b); - } - the}
You can guess what the output is.
The result is
0 S
False
Why?
Because integer is an immutable wrapper class
When B is assigned a value of 2, it is not to modify the value of the address referred to in B, but to create a new space to save as 2 and let B point to it
So where is the reference better than the pointer?
Make the program more secure Java gives you the rules. Where can I use it?
But no pointers are so flexible.
The difference between a reference to Java and a pointer to C