Learning Java, you don't necessarily know that.

Source: Internet
Author: User

As a pilgrim who is running to programming the perfect paradise, I feel that in the normal programming, should do the following points:

A: You should comment, so that it is convenient for others, but also easy to read the logic of the Code

Second: Pay attention to the details, for each line of code written for their own responsibility, for example, in the process of concurrent programming, should be to those variable shared units with "synchronous lock" or the granularity of variable shared variables to the level of each thread

Three: Pay attention to efficiency, because my school pay more attention to the algorithm this piece, then unknowingly on the program execution efficiency this piece of more persistent, if you and your colleagues have written a similar function of the program, and then the boss to you each 1 million pieces of data, your colleague's program quickly put these 1 million data Done, then went to have a cup of coffee, come back if your code is still running, this is not ... (You all know that later)

Four: Focus on the cleanliness of the code and try to minimize the redundancy of the Code, which is to be noted in the refactoring of the code.

Follow me will write some of the better examples of the algorithm I read, reading these examples is conducive to our thinking active, of course, I believe you will be like me for these algorithmic solution of the artful and marvel, so that they in the future programming more attention to this piece, these examples we can view this URL http ://www.cnblogs.com/wanggangjia/to see (Follow up on these algorithm sequences)
All right, the appetizer is over, and the dinner is here now.

1. Please refine the following functions to achieve this function: Swap the values of A and B in the following example

1  Public classTestadd {2      Public Static voidMain (string[] args) {3            intA = 100;4            intB = 10;5.....//write down your code here so that the value of a/b is exchanged6System.out.println ("A:" + A + "\ T" + "B:" + B);//Output A:10 b:1007 }  8 9}

(1) Most of us will define a temporary variable temp, and then just like the code below

int temp == = temp;

(2) Others will say, defining a variable is more extravagant! look at me.

A = a += A-= a-B;

(3) This is really better than (1) the solution, but we know that the system processing data is the fastest bit operation, we can do from this aspect to make our program faster? And it's not unsafe to assign a a+b to a that might be out of bounds? What can you do to be safe, fast, and concise? See the code below (using " XOR "operator):

A = a ^= a ^= a ^ B;

Note: An XOR operation is performed according to Bits, which is the lowest CPU bit operation, runs fast, and does not produce rounding.

Expansion: Bit operators are often used, especially the ">>" or "<<" bitwise operators, because they have a fast-running feature (think about their fast causes), so readers can look at the source code for the hashcode in the JDK.

Extension Example: Programming implementation 2 * 8, directly to the code as follows:

2<<3;  // assuming that the storage of each variable is 8 bits, then 2 of the binary is 0000 0010, the left offset 3 bits, can be 0001 0000, converted to decimal 16, not 2 * 8, 3 is because 2 3 is 8

2. This statement: float i = 3.3; can it be compiled?

float i = 3.3; cannot be compiled because the constant 3.3 Java default is double type, and the range of float type is smaller than double, assigning 3.3 to I is downward transformation, loss of precision, if really need to assign to I, Need to be forced to transform float i = (float) 3.3;

Extension: Short i = 1,i = i + 1; This is also not compiled because the Java default constant 1-bit int type, for the same reason, but short i = 1,i + 1; it is possible because the JDK implicitly casts the type to I = (short) at compile time. ) (i + 1);

What is the difference between an int type and an integer type in 3.Java?

First of all, the int type is the basic data type of Java, and the integer is an object, it is a reference, they are different in memory logic, about memory logic, can look at my writing "a junior student's learning" This article, the following gives these two types of memory structure, Since the integer is an object, then it has a lot of additional methods relative to the basic type of int, which can be self-examination of the Java API, in particular: the introduction of "Automatic unpacking and boxing" in jdk1.5, so that the basic data type and its corresponding encapsulated object can be implicitly converted.

A comprehensive example: the knowledge points covered include automatic boxing and unpacking, memory structure analysis, automatic boxing, and the idea of a similar "object pool" behind the unpacking

1  Public classBoxingtest {2      Public Static voidMain (string[] args) {3Integer i =NewInteger (300);4Integer j = 300;//Auto Boxing, internal mechanism is called valueof (int) method of integer5           intz = 300;6System.out.println (i = = j);//false because they have different memory addresses7System.out.println (z = = j);//true because J automatically unboxing, the internal mechanism is called the Integer Intvalue () method, they compare the value of the8     }9 Ten}

Read here, if you do not have a way to read the valueof (int) method of the impulse of the source, then you will lose a lot of things, because it is in the bread with Java in the performance optimization of some clues, forget, I would like to talk about it! If you don't see the source of this method, believe that the following problem is completely right should not be very likely, the first code:

1  Public classvalueoftest {//name using hump form2 3        Public Static voidMain (string[] args) {4Integer i = 50;5Integer j = 50;6Integer x = 200;7Integer y = 200;8            9System.out.println (i = = j);//trueTenSYSTEM.OUT.PRINTLN (x = = y);//false One        } A  -}

The analysis is as follows:

1   Public StaticInteger ValueOf (inti) {//Note that this is a static method that belongs to a class, so you can call the method directly using "Integer. Method Name"2  3          if(I >= integercache.low && i <= integercache.high)//the default value for Integercache.low here is -128 Integercache.high The default value is 1274              returnIntegercache.cache[i + (-integercache.low)];//These integer objects, the default range in [ -128~127], have been created and placed in a constant pool5  6          return NewInteger (i);7 8}

Since Java is all about creating objects---using objects----destroying (reclaiming) objects, because creating objects is time-consuming and loss of system performance, we typically initialize some instances at the beginning of the program for objects that are more time intensive but often used in our programs. This is true of the object pool object, which is how the thread pool's threads are, and the connection object of the database connection pool, which we call in the program to achieve reuse and quick reference of objects, is a way to optimize the function of the program. All right! Back to the point, the integer object in [ -128~127] has been initialized in the constant pool, so the integer object in this interval will point to the corresponding object in the constant pool, which is why the first output is true in the code above. Outside of this range, it creates an integer object itself, so it's not equal according to the memory logic, so it's false.

In fact, have the time to read Java source code is also good, here, I just hope that programmers in the normal code editing, always pay attention to the security of their own programs, the efficiency of code operation and optimization of project performance and so on

Learning Java, you don't necessarily know that.

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.