Java (Introducing an intermediate variable, without introducing intermediate variables) to exchange the values of two variables

Source: Internet
Author: User

First, describe

Exchange two numbers without introducing other variables, introduce a variable to mediate, and exchange two number values.

Second, the source code

<span Style= "FONT-SIZE:18PX;" >package Tong.yue.sort;public class Swaptwovalues {/** * @param args */public static void main (string[] args) {int a = 10,b = 20;swapbyextravariable (A, B), Swapbyself (A, B);//The value is passed here, just copy a A, B copy to participate in the operation of the function, does not affect the original values of A and B in the main function System.out.println ("Main function:a=" +a+ ", b=" +b);}   private static void Swapbyself (int a, int b) {//Exchange two numbers without introducing other variables, make a = A+b using the sum of two numbers; A holds two numbers and B = a-b;//Two and-B, which is AA = a-b;//Two and-B, at which point B has become a, so it is equivalent to Sum-a=bsystem.out.println ("Swapbyself first function:a   = "+a+", b= "+b);//There is another way to use the difference of two numbers, that is, the distance between two numbers a = b-a; A= the difference between b = b-a;//b = The original B-two number of distance = = The original AA = a+b;//The difference between the final a= and the original a== the original BSystem.out.println ("Swapbyself second function:a=" +a+ ", b=" +b);//change back}private static void swapbyextravariable (int a, int b) {//introduce a variable to do mediation, exchange two number int temp = A;a = B;b = Temp;s Ystem.out.println ("swapbyextravariable function:a=" +a+ ", b=" +b);}} </span> 

iii. Results of Operation


Java (Introducing an intermediate variable, without introducing intermediate variables) to exchange the values of two variables

Related Article

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.