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!