(10.16) Java Small job!

Source: Internet
Author: User

I believe you have just learned Java more or less will write some Java BASIC programming to practice the feel, I am no exception! Today I would like to share with you some of the more interesting Java applets I have been exposed to recently!

Given that a has been assigned and B has been assigned, write a Java program that swaps the value A and B:

In fact, this problem is very classic, whether it is C language or Java, all of this problem as the entry of the small job, its solution is as follows:

1  Public classdemo{2      Public Static voidMain (string[] args) {3         intA=1;//assign a value to a4         intb=2;//assign a value to B5         inttemp=a;//a new variable6A=b;7B=temp;//a and B interchange8   }  9}

The way to solve this problem is usually to initialize a new variable, which is used as an intermediate variable to prevent a or b from being overwritten, and to solve the problem in this way. So, there are other ways to solve this problem besides the usual method?

The answer is yes, I will give you a list of two ways to solve the problem, there are other ways to solve the problem is also welcome to add!

  1. Add and Subtract

 Public class Demo {    publicstaticvoid  main (string[] arg) {        int a = 1;         int b = 2;         = B-a        ; = B-a        ; = B +A;    }}

  2. XOR law

 Public class Demo {    publicstaticvoid  main (string[] arg) {        int a = 1;         int b = 2;         = a^b;         = a^b;         = a^b;    }}

  In fact, whether it is the addition or subtraction, different or law, these two methods of solving the problem is the extension of our thinking, but also the logic of our thinking of a change, after all, Java is a pile of bricks, all of them through a step by step combination to complete, and the completion of what depends on our way of thinking and imagination, So do not just limit to a solution, to the courage to expand their thinking, change their own logic, to find a more interesting world!

(10.16) Java Small job!

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.