On the issue of exchanging two numbers

Source: Internet
Author: User

Walnuts, posterity


Contents of this lecture: about two numbers exchanged


for In Java, for a basic data type, Java passes a copy copy and cannot change the value of the parameter at all. You can do this through an array, because the array passes the address.

Example one:

public class Text {public    static void Main (string[] args) {      int a=4;    int b=5;        Change (A, b);          System.out.println ("main function:" +a+ "," +b);    }            public static void Change (int a, int b) {          int temp;          temp = A;          A = b;          b = temp;          SYSTEM.OUT.PRINTLN ("Swapped data:" + A + "," + b);      }  }

Output:

Data exchanged: 5, 4 main function: 4,5


Example two:

public static void Change (int a, int b) {      //In this implementation, only the two variables themselves are different//or implemented.          A = a ^ b;          b = a ^ b;          A = a ^ b;          SYSTEM.OUT.PRINTLN ("Swapped data:" + A + "," + b);      }  

Example three:

public static void Change (int a, int b) {      //In this implementation, only the two variables themselves are added minus the implementation.          A = a + B;          b = a A;          A = a-B;          SYSTEM.OUT.PRINTLN ("Swapped data:" + A + "," + b);   }  


Example four:

public class Text {public    static void Main (string[] args) {      int[] a = new int[2];        A[0] =4;        A[1] =5;        Change (A, 0, 1);        System.out.println ("main function:" +a[0]+ "," +a[1]);    }            public static void Change (int[] A, int x, int y) {       int temp = a[x];         A[X] = A[y];         A[y] = temp;         System.out.println ("Post-Exchange data:");        System.out.println ("x=" + a[0]);        System.out.println ("y=" + a[1]);    }  }

Output:

Data exchanged: x=5y=4 main function: 5,4


This is where we go, take your time and enjoy it

On the issue of exchanging two numbers

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.