JAVA programming specifications

Source: Internet
Author: User
Tags file separator

In this article, I want to chat with some specifications related to the Java language with a smile.

 

 

1. Basic data types.

Do you still remember the example at the end of the previous article?

Because of the binary mechanism of the computer, the Java language (similar to other languages) cannot accurately calculate float and double data. Therefore, you need to consider using BigDecimal for these calculations.

 

2. String and StringBuffer classes

Java's String class provides the following simple String connection methods.

String s1 = "";

String s2 = "B ";

String s3 = "c ";

String s = s1 + s2 + s3;

However, there is a problem here that every addition operation of the String class will generate a new object. When you start to increase the number of operations on the String class, not only will the memory usage of the program increase significantly, but the program running time also increases significantly. In this case, consider the append method of the StringBuffer class. A smile is not an exists. Therefore, a smile is a kind of preference. Do not use the append method as long as the string is added. However, you should make your own measurement based on the actual situation. For specific tests, you can write a for loop for times, which is easy to test.

 

3. About import *

Try not to use the import * statement, but to write out the classes to be imported. One reason is that the write method of import * affects program reading, and the maintainer is not very clear about the classes you use. But more importantly, if you import *, all classes represented by * will be packaged when you package and generate jar, war, and other files. On the one hand, the size of your published content is greatly increased, and some content that you do not want to disclose may be leaked. This is the key to the problem, and security is the first.

 

4. Use exception handling properly. Do not use it excessively.

Exception Handling in Java is a good thing. This can save us a lot of work. However, the running time of code segments with exception handling is much longer than that without exception handling. Therefore, do not submit everything to exception handling. We should make appropriate judgments. At the end of the process, we should hand over things that cannot be processed to Exception Handling. This is also in line with the business processing logic.

For example, FileNotFoundException exists. However,

Try {

} Catch (FileNotFoundException ){

}

Not as good

If (f. exists ()){

} Else {

}

 

5. Try not to catch Exception exceptions easily.

Because the old exceptions in Java will be overwhelmed by new exceptions, it is difficult for us to determine exactly what the problem is based on the new exception information. A simple Exception capture greatly increases this possibility. In addition, simply capturing Exception exceptions makes it difficult for us to take corresponding measures against different exceptions. Therefore, try to catch specific exceptions instead of Exception. Consider the following code structure.

Try {

} Catch (){

} Catch (){

} Catch (Exception ){

}

 

The old exceptions in Java will be overwhelmed by new exceptions. Generally, You need to implement some exception classes by yourself, because they are not the focus of this article, we do not intend to discuss it here.

 

6. do not generate your object repeatedly. A new object in Java takes a relatively long time. Although the current CPU may not care much about the time. However, the accumulation is much lower. Maybe you should try not to create a new one twice. What we can see in the current phase is to remove your object in the circulating body rather than in the circulating body, which is very simple and easy to notice. However, in a complex system, how to minimize the number of times you create an object and whether you need to use the static keyword is not so obvious is easy to consider and solve. Considering maintainability, code structure, and other factors, the trade-off angle is also different. At least, remember this principle first. Do not generate your object repeatedly.

 

 

7. Do not perform unnecessary calculations in your loop body. For example:

For (; al. size ()){}

Worse:

Int size = al. size ();

For (; size ){}

Although I have read the article, it seems that the Java compiler will be optimized, the two statements are the same. But the basic principle is "do not perform unnecessary calculations in your loop ." I don't think there will be any different opinions. I don't like to remember so many things with a smile. There is no commitment to the Optimization done by the compiler. You can still feel at ease by yourself. Of course, when the latter method seriously affects the readability of your code, you can make a trade-off between efficiency and readability. After all, the current CPU is still very powerful. If the number of cycles is not many, the impact of efficiency is negligible.

 

8. String = and equal ()

When the string is equal, = determines whether the address is the same, equal () determines whether the character value is the same. Most of the time = is the same as equal. This is because the String object is in the constant mode. If you do not explicitly Create a new String object, the new String object is stored in a buffer by default in Java, then, each time you determine whether the buffer zone already has this object, if so, then the String object created with the same character value will also point to the address of the originally created object with this character value. That is to say, when the character values are the same, the geological conditions are the same in most cases. = The same effect as equal. However, when the object is generated by str = new String ("abc") instead of directly assigning values like str = "abc", or after some String connection processing, or, if it is generated by StringBuffer and other objects, a new address is opened in the memory. At this time, the = and equal () results are different.

 

Is it a little complicated? Here we need some understanding about memory, stack, and Object Storage. I don't want to get stuck in this discussion with a smile. If you cannot understand it, remember to use equal () instead of =, as for when to use =, I think you will naturally understand when you need it. In fact, we seldom need = for string judgment.

 

9. About str. equal ("abc") and "abc". equal (str)

There seems to be a lot of arguments. The first constant may be followed by most people's habits and our logic thinking. However, you need to determine whether another str is null. Otherwise, exceptions may occur. The other method does not need to judge whether the statement is null. For personal preferences, the latter method is preferred.

10. Does Java pass a value or a reference?

Once, Java programmers switched from C ++. What everyone loves to talk about most is this highly practical but boring question. I don't know what it is called "pass value" or "transfer reference" with a smile. I just want to remind you to remember the following facts with a smile. It is enough to remember them. In the end, does this fact mean to argue whether Java transfers values or references?

In fact, in a method, the parameter object itself cannot be changed. For example:

Private void changeParam1 (XXXClass _ pc ){

_ Pc = new XXXClass (); // you want to change the parameter object itself.

}

The _ pc = new XXXClass (); operation in the above Code takes effect only within the function body. In addition to the function body, what is the object you pass to this function. That is to say, you cannot change the memory address that the parameter points to within the function. You cannot change the parameter object itself. Here, the debate arises from a function that C ++ programmers like very much as Swap, which cannot be implemented in Java.

However, attributes of parameter objects can be changed in Java.

Private void changeParam2 (XXXClass _ pc ){

_ Pc. setField (fieldValue) // you want to change the attributes of the parameter object.

}

The above code can achieve your intention.

 

As for the reason, it is necessary to store objects in the painting memory so that the object can be clearly indicated. Smile and feel that there is no research value. Just remember the conclusion. Drawing is so tired that you will be lazy when you smile.

11. Take Java's cross-platform into account and try to use the functions provided by Java.

For example, if a newline carriage return is "r" n "or" r "or" n ", different systems are different. So consider using the functions provided by Java.

Public staticString GetProperty(StringKey) method, where the key can take the following values.

File. separator

File separator ("/" in UNIX)

Path. separator

Path separator (":" in UNIX)

Line. separator

Line separator ("/n" in UNIX ")

 

Smile fat LAN original, reprint please note.

Bluesmile979@hotmail.com 

Http://blog.csdn.net/bluesmile979/archive/2008/10/19/3105274.aspx

 

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.