1. Accessing non static member variables in static methods (for example, in the main method)
Many programs that have just come into contact with Java will have a problem, that is, accessing member variables in the main method. The main method is generally marked as "static", which means that we do not need to instantiate this class to call the main method. For example, the Java virtual machine can call the MyApplication class in this form:
MyApplication.main (command line parameter);
The MyApplication class is not instantiated here, or no member variables are accessed here. For example, the following program will produce a compiler error.
public class StaticDemo { public String my_member_vaiable = "somedata"; public static void main (String args[]) { // Access a non-satic member from static method System.out.println ("This generates a compiler error"+ my_member_variable); } }
If you want to access a member variable in a static method (such as the main method), you need to instantiate an object. The following code example shows how to correctly access a non static member variable. The method is to instantiate an object first.
public class NonStaticDemo { public String my_member_variable = "somedata"; public static void main (String args[]) { NonStaticDemo demo = new NonStaticDemo(); // Access member variable of demo System.out.println ("This WON'T generate an error"+ demo.my_member_variable); } }
2. Typing the method name incorrectly during overloading allows the programmer to overwrite the method implementation with new code
Overloading is a convenient feature, which is widely used by many object-oriented programmers. If you use AWT 1.1's time processing model, you usually override the listener method to implement customized functions. An easy mistake to make when overloading a method is to mistype the name of the method to be overloaded. If you enter the method name incorrectly, you are not overloading the method. On the contrary, you are redefining a method, but the parameters and return types of this method are the same as those of the method you want to overload.
public class MyWindowListener extends WindowAdapter { // This should be WindowClosed public void WindowClose(WindowEvent e) { // Exit when user closes window System.exit(0); } }
This method won't compile, so it's easy to catch it. In the past, I have noticed a method, believed that it was called, and spent a lot of time looking for the error. The performance of this error is that your method will not be called. You think your method has been skipped. A feasible solution is to add a printout statement. Record the information in the log file. Or use trace debugger (such as VJ + + or Borland JBuilder) to debug line by line. If your method can't be called yet, it's likely that you typed the method name incorrectly.
3. Comparison and allocation ("=" is better than "= =")
When we use the = = operator, we are actually comparing the references of two objects to see if they point to the same object. For example, we cannot use the = = operator to compare whether two strings are equal. We should use. equals method to compare two objects. This method is common to all classes and inherits from java.lang.Object.
Here is the correct way to compare the equality of two strings:
// Bad way if( (abc + def) == "abcdef" ) { ...... } // Good way if ( (abc + def). equals("abcdef") ) { ...... }
4. Confusing value passing and reference passing
This is a mistake that is not easy to find. Because when you look at the code, you will be very sure that this is a reference passing, but it is actually a value passing. Java uses both, so you need to understand when you need value passing and when you need reference passing. When you want to pass a simple data type into a function, such as char, int, float or double, you are passing a value. This means that a copy of this data type is copied, which is passed to the function. If the function modifies the value, only the copy of the value is modified. After this function is completed, it will return to the control calling function. At this time, the "real" value is not affected and no changes are stored.
If you want to modify a simple data type, you can locate the data type as a return value or encapsulate it in an object.
When you want to pass a java object into a function, such as an array, a vector or a string, what you pass is a reference to an object. The string here is also an object, not a simple data type. This means that if you want to pass an object to a function, you have to pass the reference of the object instead of copying it. Any change to the member variables of this object will persist. The quality of this change depends on whether you do it deliberately.
It should be noted that if the string does not contain any method to change its value, you'd better pass it as a value.
5. Write an empty exception handler
I know that an empty exception handling is as tempting as ignoring errors. But if an error does occur, you will not get an error message output, which makes it unlikely to find the cause of the error. Even the simplest process is very useful. For example, add try{}catch {} to your code to try to catch any throw and print out the error message. You don't have to write custom handlers for every exception (although it's a good programming habit). But don't leave this exception handler empty, or you won't know what error has occurred.
give an example:
public static void main(String args[]) { try{ // Your code goes here } catch (Exception e) { System.out.println ("Err - " + e ); } }
6. Forget that the index in java starts at 0
If you have a C/C + + programming background, you won't find the same problem when using other programming languages.
In java, the index of the array starts from 0, which means that the index of the first element must be 0. Confused? Let's look at an example
// Create an array of three strings String[] strArray = new String[3]; // First element's index is actually 0 strArray[0] = "First string"; // Second element's index is actually 1 strArray[1] = "Second string"; // Final element's index is actually 2 strArray[2] = "Third and final string";
In this example, we define an array with three strings, which is subtracted when we access its elements. Now, when we try to access strArray[3], that is, the fourth element, an ArrayOutOfBoundsException exception will be thrown. This is the most obvious example - forgetting the 0 index rule.
Elsewhere, 0 indexing rules can get you into trouble. For example, in a String. Suppose you want to get a character from the offset determined by a String, use String. charAt (int) function, you can see this information. However, in java, the index of String class also starts from 0, which means that the offset of the first character is 0 and the second is 1. You may get into some trouble. If you don't pay attention to this problem, especially if a large number of String handlers are used in your application, you are likely to use the wrong characters, At the same time, a StringIndexOutOfBoundsException is thrown at runtime, just like the ArrayOutOfBoundsException exception. The following examples demonstrate these:
public class StrDemo { public static void main (String args[]) { String abc = "abc"; System.out.println ("Char at offset 0 ; " = abc.charAt (0) ); System.out.println ("Char at offset 1 ; " = abc.charAt (1) ); System.out.println ("Char at offset 2 ; " = abc.charAt (2) ); // This line should throw a StringIndexOutOfBoundsException System.out.println ("Char at offset 3 ; " = abc.charAt (3) ); } }
At the same time, it should be noted that the 0 index rule should not only be applied to arrays or strings, but also to other parts of Java. But not all of them. Java.util.Date and java.util.Calendar. The month of these two classes starts from 0, but the date usually starts from 1. The following program proves this.
import java.util.Date; import java.java.util.Calendar; public class ZeroIndexedDate { public static void main (String args[]) { // Get today's date Date today = new Date(); // Print return value of getMonth System.out.println ("Date.getMonth() returns ; " + today.getMonth()); // Get today's date using a Calendar Calendar rightNow = Calendar.getInstance(); // print return value of get ( Calendar.MONTH ) System.out.println ("Calendar.get (month) returns ; " + rightNow.get (Calendar.MONTH)); } }
7. Prevent threads from accessing in parallel in shared variables
When writing a multithreaded application, many programmers like to cut corners. This will lead to thread conflicts in their applications or applets. When two or more threads access the same data, there is a certain probability (the probability depends on Murphy's law) that two threads access or modify the same data at the same time. Don't be foolish to think that this won't happen in a single threaded application. When accessing the same data, your thread is likely to be suspended, and when the second thread enters, it will overwrite the modification of the first thread.
Such problems do not occur only in multithreaded applications or small applications. If you write java APIs or Java beans, your code is probably not thread safe. Even if you've never written a separate application that uses threads, people may use your program. For the sake of others, not just you, you should take measures to prevent threads from accessing in parallel in shared variables.
How to solve this problem? The simplest is to privatize your variables. Synchronous access method is also used. Access methods allow access to seemingly member variables, but only in a control mode. The following access method can modify the value of the counter in a safe way.
public class MyCounter { private int count = 0;//count starts at zero public synchronized void setCount(int amount) { count = amount; } public synchronized int getCount() { return count; } }
8. Capitalization error
This is one of the most common mistakes we make. It is very simple, but sometimes we can't find the error when we look at a variable or method without uppercase. I am often confused because I think these methods and variables exist, but I can't find that they are not capitalized.
You can't check it with silver bullets here. You can only train your own trainers to reduce this error. Here's a trick:
Method and variable names used in Java APIs should start with lowercase letters.
All new words for variable and method names should start with capital letters.
If you define your variable name and class name in this way, you are consciously making them right, and you can gradually reduce the number of such errors. This may take some time, but it is possible to avoid more serious errors in the future.
This is the most common mistake made by java programmers!!!
9. Null pointer
Null pointers are the most common mistake java programmers make. The compiler won't check this error for you. It only shows it at runtime. If you can't find it, your users are likely to find it.
When trying to access an object, the reference of the object is empty, and a NullPointerException exception will be thrown. There are many reasons for null pointer errors, but generally, this error means that you do not initialize an object, or you do not check the return value of a function.
Many functions return a null to indicate that an error condition has been executed. If you don't return the value, you can't know what happened. Since the reason is a wrong condition, the general test will not find it, which means that your users may find it for you at the end. If the API function indicates that an empty object is likely to be returned, be sure to check before using the reference of the object.
Another reason may be that you are not standardized when initializing an object, or its initialization is conditional. For example, check the following code to see if you can find this error.
public static void main(String args[]) { // Accept up to 3 parameters String[] list = new String[3]; int index = 0; while ( (index < args.length) && (index < 3 ) ) { list[index++] = args[index]; } // Chexk all the parameters for (int i = 0; i < list.length; i++) { if (list[i].equals"-help") { //...... } //else...... } }
The above code (as an example), shows the usual errors. In some cases, if the user enters three or more parameters, the above code will work normally. However, if no parameters are entered, you will get a null pointer exception at run time. Sometimes your variables will be initialized, but other times they won't. A simple solution is to check that the array element is very empty when you access it.