2. Object operation prone to nullpointexception errors
3. Redundant processing statements
4. Parameter transfer problem
5. Exception Handling
6. Database Operation problems
7. Index out of Bounds
8. Other
9. Issues to be discussed
1.Java Compile Run problem
Java Program files must first be compiled into a byte-code class file, and then run through the JVM. Java is platform-independent because it provides the JVM (Java Virtual machine) for almost the majority of the operating system, so that we need to use a unified API instead of the underlying system.
In the early days of using Java, most of the problems I am afraid of is java.lang.ClassNotFoundException and Java.lang.NoClassDefFoundError, which is mainly the problem of classpath settings, Similar to the dynamic link library in C + +, if your source inside the use of other package APIs, so that you are in the development and operation of the time you have to set it to the classpath inside, set up when you can point to a directory, Typically a directory containing the required classes, or point to a jar or zip file, which is a classes packaged file. Such as:
Set Classpath=c:\jdk1.3.1\lib\tools.jar;d:\develop\csc\class
Run under Windows command
Set Classpath
You can view classpath that are currently set, and if you want to run an append setting:
Set Classpath=%classpath%;c:\bea\wlserver6.1\lib\weblogic.jar;
If you use the command line to run the compilation, you have to set the JDK path. Such as:
Set path=c:\jdk1.3.1\bin;%path%
Of course, if you're not bothered, you can specify a full path:
C:\jdk1.3.1\bin\javac Yourown.java
C:\jdk1.3.1\bin\java Yourown
Classpath can also be specified when the runtime is running. Such as:
Javac–classpath%my_classpath% Yourown.java
Java–classpath%my_classpath% Yourown
In general, the JVM is running with the default load classes, you can run Java–verbose for viewing, generally%jdk_home%\jre\lib below I18n.jar and Rt.jar, If you put your jar file under the EXT directory below this directory, you do not need to specify it, the JVM will automatically load these jars.
Also note that when you run class, you use the class's full name, which contains its package name, if there is a class declaration as follows:
Package Cn.com.sunjapan.util
public class Stringutil {
public static void Main (string[] args) {
System.out.println ("Hello World");
}
}
You have to use it when you run it.
Java cn.com.sunjapan.util.StringUtil
You can't use the Java stringutil or you'll get java.lang.NoClassDefFoundError.
2. Object operation prone to nullpointexception error
This error is probably the easiest mistake to make in the early stages of programming. Java is an object-oriented language, almost all operations are between objects, the instance of a class if it is empty (null) can not invoke the method of this instance, otherwise it will be a java.lang.NullPointException error. The most common string operation, such as:
String str = NULL;
if (Str.equals ("Hello")) {
System.out.println ("str is Hello");
}
The common way to avoid this is to judge whether it is null before using an object, unless you are sure it is not null. The following example is modified as follows:
String str = NULL;
if (str!=null && str.equals ("Hello")) {
System.out.println ("str is Hello");
}
This equals or equalsignorecase operation for string can often be safely manipulated in the following ways:
String str = NULL;
if ("Hello". Equals (str)) {
System.out.println ("str is Hello");
}
Use a certain non-nullable string to compare to an unknown string.
3. Redundant processing statements
This problem, of course, is not only in Java, any program is likely to have redundant garbage, although the end result is correct, we write the program to avoid this unnecessary processing.
Common situations include the following:
More than 3.1 instances of construction
Declares an instance of an object, some people like to new at the same time, that is, allocated space, but in the back and not to allocate space, but did other operations, for example:
ArrayList resultlist = new ArrayList ();
try {
Resultlist = Somemodule.getresultlist ();
catch (Exception e) {
return null;
}
...
Resultlist the space at the same time as it was declared, but it points to the other returned address below. Although we do not have to consider the problem of memory allocation when writing Java programs, Java has its own set of memory management mechanism, but Java in the construction of the object is very expensive, so the waste of the efficiency of such treatment must be avoided.
3.2 Cycle Redundancy
We often use loops from an array or collection to find a qualifying element to operate on, and often forget to jump out of the loop when it's done. Cases:
If the above procedure is only to find out if there is a tue in the week, then you should jump out of the loop after finding the correct way to write the following:
for (int i = 0; i < week.length; i++) {
if (Week[i].equals ("Tue")) {
System.out.println ("Tue is found");
Break (or it is possible to return)
}
}
...
The principle of cyclic processing is to jump out of the place where it has been processed.
3.3 Repeating statements
It is recommended that if you have two or more places where you need to use the same block code, consider using a function, if a function block is more independent, it is possible to be called at other times, and this time as far as possible to use the method independently.
There is also a situation in the Conditional branch statement, each branch needs to execute a certain same statement, this time need to mention the outside of the branch to execute, here are a few examples:
Ø Use method
public void SomeMethod1 () {
...
String str = "This is a sample";
A certain processing of STR, returning a new str
if (str!= null) {
str = ...;
}
...
}
public void SomeMethod2 () {
...
String str = "This is a sample";
A certain processing of STR, returning a new str
if (str!= null) {
str = ...;
}
...
}
The function of the blue font part can be done in a separate way, so it is OK to call the same method in two places. In the later maintenance and other aspects are helpful, do not go everywhere to find. Rewrite as follows:
public void SomeMethod1 () {
...
String str = "This is a sample";
str = GETSOMESTR (str);
...
}
public void SomeMethod2 () {
...
String str = "This is a sample";
str = GETSOMESTR (str);
...
}
/**
* A certain processing of STR, returning a new str
*/
private string Getsomestr (String str) {
if (str!= null) {
str = ...;
}
return str;
}
Ø Statement Merging
...
if (expression1) {
...
Somestatement;
else if (expression2) {
...
Somestatement;
} else {
...
Somestatement;
}
...
Or
Switch (flag) {
Case RESULT1:
...
Somestatement;
Break
Case RESULT2:
...
Somestatement;
Break
Default
...
Somestatement;
Break
The blue font is part of the section that is executed on each of the conditional branches, so it is not written in each branch, but is called outside the conditional statement, and rewritten as follows:
...
if (expression1) {
...
else if (expression2) {
...
} else {
...
}
Somestatement;
...
Or
Switch (flag) {
Case RESULT1:
...
Break
Case RESULT2:
...
Break
Default
...
Break
}
Somestatement;
4. Parameter transfer problem
4.1 General Object Delivery
When calling a method that requires passing parameters, if the parameter is an object, the default is to pass the address, similar to the pointer in C/s, which Java calls "handle". Cases:
public class Testpassparam {
public SomeClass param = new SomeClass ();
public void Processparam (SomeClass newparam) {
System.out.println (Newparam = = param);
}
public static void Main (string[] args) {
Testclassparam Testclassparam = new Testclassparam ();
The result should return true; Because they point to the same handle, that is, the address is the same. If the parameter is a base data type, it is passed by value, and Java does not pass as a reference like C.
Where MyForm is an object, it is passed to Processactionform to do processing, first with another otherform to pick up, this time Otherform also point to MyForm handle, and in the outside to use MyForm to connect return value , MyForm this time actually pointed to the original handle. While the result is true, there is a problem with two aliases pointing to the same handle at the same time. A method of executing either of these aliases, and the object of the other alias changes as well. So the above example should be rewritten as follows:
Especially when passing parameters between images, you have to be careful unless you can ensure that your data is not tampered with, or you need to clone an object to pass through and then take the return value.
Note: If parameters are passed between the EJB's client and server, no handle is passed and the client side does not change the data after the server-side modification. Because they are transmitted over the network by an object byte stream, there is no condition for the same handle address. You can use it with ease, and finally if the client side needs to use this new object again, you need to return to the past. (EJB2.0 supports the local interface, in which case it is possible to pass the same handle as previously mentioned, never tried).
The particularity of 4.2 string
String is designed as a secure string in Java, and for either operation of String, a copy of string is regenerated first, and then the copy is manipulated. So a string can be considered a value pass when the parameter is passed. That is, if you need to modify a string and return the modified string, you will have to answer the return value again. Such as:
String str = "This is a sample";
str = EDITSTR (str);
System.out.println (str); "Here is a sample"
private string Editstr (String str) {
String newstr = str. substring (4);
Newstr = "Here" + newstr;
return newstr;
}
If you want to pass a handle, you can use a class stringbuffer used by the internal operation of String, which operates on the same object, so the efficiency is naturally higher. The example above is rewritten with StringBuffer as follows:
StringBuffer str = new StringBuffer ("This is a sample");
Editstr (str);
System.out.println (str); "Here is a sample"
private void Editstr (StringBuffer str) {
Str.replace (0, 4, "here");
}
5. Exception Handling
Some beginners are accustomed to using the return value for error handling, and using exception handling will make the program structure more reasonable and more efficient. For example, the client side needs to use EJB for DB operations, and the client side needs to know if DB processing is wrong, through layers of upward throw exception, until the client side needs to deal with the place to intercept, and then make exception handling. Such as:
Background db Processing:
public static Java.sql.Timestamp Getdbsysdate () throws Cscwebexception {
Connection conn = null;
Timestamp systime = null;
try {
conn = Pjejbsvrutil.getwlpoolconnection ();
Systime = commondao.getdbsysdate (conn);
catch (SQLException CE) {
throw new Cscwebexception (Ce.getmessage ());
finally {
try {
IF (conn!= null) {
Conn.close ();
}
catch (Exception e) {
throw new Cscwebexception (E.getmessage ());
}
}
return systime;
}
At the front desk:
try {
Commonintf.getdbsysdate ();
catch (Cscwebexception CeX) {
Cat.debug ("", CeX);
Return Getexceptionforward (CeX);
}
In order to prevent unauthorized handling, unless you definitely do not need to deal with, the promotion of exception in the face of the time to be thrown up, by the final call to deal with, of course, can not generalize, depending on the situation. For example, I think the exception in the method of the body to be resolved, give a CSC in the emergence of bugs.
public boolean Checktelformat (String telno) {
Boolean error = FALSE;
if (Telno = null | | telno.equals ("")) {
Error = TRUE;
} else {
if (Ejb.util.StringUtil.chkPhone (Telno)) {
Error = FALSE;
} else {
Error = TRUE;
}
}
if (Telno.startswith ("184") | | | Telno.startswith ("186")) {
if (telno.length () = = 3) {
Error = TRUE;
}
}
if (Error) {
Objmngr.showerror ("mcstc001e");
Cmbtelno.requestfocus ();
return false;
} else {
return true;
}
}
Using a flag to remember the results of each check, and then at the end of the error Dialog, this is a more typical c of the wording, rewrite as follows:
public boolean Checktelformat (String telno) {
try {
if (Telno = null | | telno.equals ("")) {
throw new Exception ();
} else {
if (!ejb.util.stringutil.chkphone (Telno)) {
throw new Exception ();
}
}
if (Telno.startswith ("184") | | | Telno.startswith ("186")) {
if (telno.length () = = 3) {
throw new Exception ();
}
}
catch (Exception e) {
Objmngr.showerror ("mcstc001e");
Cmbtelno.requestfocus ();
return false;
}
return true;
}
Using the method of throwing exception, at the end of the method to intercept, such a encounter error can be dealt with immediately, from the efficiency of the highest.
6. Problems with database operations
Based on existing development experience, we typically fetch connection in Sessionbean (or a module Bean without EJB) and then invoke methods in the specialized operations database (DAO). That is, the connection open and close operation in the bean, and the statement and ResultSet operations in the DAO are generally required to close them at the end. Following the example in section, there is a method in Commondao:
public static Java.sql.Timestamp Getdbsysdate (Connection conn)
Throws Cscwebexception {
Statement stmt = null;
ResultSet rs = null;
Timestamp systime = null;
try {
stmt = Conn.createstatement ();
rs = Stmt.executequery ("Select Sysdate from DUAL");
if (Rs.next ()) {
Systime = Rs.gettimestamp ("Sysdate");
}
catch (SQLException CE) {
throw new Cscwebexception (Ce.getmessage ());
catch (Exception e) {
throw new Cscwebexception (E.getmessage ());
finally {
try {
if (Rs!= null) {
Rs.close ();
}
if (stmt!= null) {
Stmt.close ();
}
catch (Exception e) {
throw new Cscwebexception (E.getmessage ());
}
}
return systime;
}
The statements in finally are always executed, so even if the SqlException is thrown above it will perform the close operation of stmt and Rs.
7. Index out of Bounds
The index crosses the line including many:
Index of Østring
The index of a string starts at 0, and the maximum is its character length. Commonly used for substring this method:
String str = "This is a sample";
Str.substring (5, 7); returns to IS;
Str.substring (15, 16) or str.substring (15); Returns the last character E;
Str.substring (16, 17); This will throw java.lang.StringIndexOutOfBoundsException error;
Ø array Subscript
The array subscript is also started with 0, with a maximum length of 1, for example:
COLUMNLEN[8] will throw java.lang.ArrayIndexOutOfBoundsException errors.
Øvector, ArrayList and other collection size
Vector and ArrayList belong to the list, they are all ordered aggregates, and the subscript is also starting at 0, and the maximum is length-1, and unlike arrays, their elements must all be object, but they can be of different types, but they have to be typed after they are taken out. The array must have the same type of all elements. ArrayList after construction, if there are no elements in the case, the call to set (index, Object) will be an error. You have to do the Add (Object) first. Cases:
ArrayList list = new ArrayList (10); This place's 10 is the initial capacity of the list, does not mean that it has 10 elements, this is different from the array, the array in this case has 10 initial values, the initial value with the specific element type, the general object is null;
List.set (0, "a"); Will throw Java.lang.IndexOutOfBoundsException
List.add ("a");
List.set (0, "new"); Correct because the element already exists in position 0
8. Other
Specific to each project, the use of different APIs may also encounter some common problems. Need to do the necessary training at the beginning of the project, often give a good sample will be twice the effort.
Some questions are not described in detail here:
U Case Problem (String.Equals () with string.equalsignorecase (), variable name, etc.)
U-Bracket matching problem
U...
9. Issues to be discussed
9. 1 Method Return Location
private int GetStatus (String sflag) {
if (CodeBook.STATUS_OK_NAME.equals (Sflag)) {
return codebook.status_ok_value;
else if (CodeBook.STATUS_OK1_NAME.equals (Sflag)) {
return codebook.status_ok1_value;
else if (CodeBook.STATUS_NG_NAME.equals (Sflag)) {
return codebook.status_ng_value;
}
return codebook.status_ng_value;
}
And
private int GetStatus (String sflag) {
int istatus = Codebook.status_ng_value;
if (CodeBook.STATUS_OK_NAME.equals (Sflag)) {
Istatus = Codebook.status_ok_value;
else if (CodeBook.STATUS_OK1_NAME.equals (Sflag)) {
Istatus = Codebook.status_ok1_value;
else if (CodeBook.STATUS_NG_NAME.equals (Sflag)) {
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