Java issues to be aware of 1

Source: Internet
Author: User

I. Returning an empty collection first rather than null

If the program is going to return a collection that does not contain any values, make sure to return an empty collection instead of NULL. This can save a lot of "if else" checks.

 Public class getlocationname {    return (null==cityname?) "": CityName);}
Two. Manipulate strings with caution

If two strings are spliced with the + operator in A For loop, each loop produces a new string object. This not only wastes memory space but also affects performance. Similarly, if you initialize a string object, try not to use the constructor method, but rather initialize it directly. Say:

// Slower instantiation New String ("Yet another string object"); // Faster Instantiation String good = "yet another string object"
Three. Avoid useless objects

Creating objects is one of the most expensive operations in Java. It is therefore better to create/initialize objects when necessary. As follows:

Importjava.util.ArrayList;Importjava.util.List; Public classEmployees {PrivateList Employees;  PublicList GetEmployees () {//Initialize only when required        if(NULL==Employees) {Employees=NewArrayList (); }        returnEmployees; }}
Four. The contention between arrays and ArrayList

Developers often find it difficult to choose between arrays and ArrayList. They each have their own merits and demerits. How to choose should be subject to availability.

Importjava.util.ArrayList; Public classArrayvsarraylist { Public Static voidMain (string[] args) {int[] MyArray =New int[6]; myarray[7]= 10;//arraysoutofboundexception//Declaration of ArrayList. Add and Remove of elements are easy.Arraylist<integer> myarraylist =NewArraylist<>(); Myarraylist.add (1); Myarraylist.add (2); Myarraylist.add (3); Myarraylist.add (4); Myarraylist.add (5); Myarraylist.remove (0);  for(inti = 0; I < myarraylist.size (); i++) {System.out.println ("Element:" +Myarraylist.get (i)); }        //Multi-dimensional Array        int[][][] MultiArray =New int[3] [3] [3]; }}
    • Arrays are fixed-length, and ArrayList are variable-length. Since the array length is fixed, the memory is already allocated when the array is declared. The operation of the array is faster. On the other hand, if we do not know the size of the data, then too much data will lead to arrayoutofboundexception, and less will waste storage space.
    • ArrayList is simpler than arrays in terms of adding and deleting elements.
    • Arrays can be multidimensional, but ArrayList can only be one-dimensional.
    • The finally block of the try block is not executed

Look at the following code:

 Public classShutdownhooksdemo { Public Static voidMain (string[] args) { for(inti=0;i<5;i++)        {            Try {                if(i==4) {System.out.println ("Inside Try block.exiting without executing Finally Block."); System.exit (0); }            }            finally{System.out.println ("Inside Finally Block."); }        }    }}

From the code point of view, it seems that the println statement in the finally block should be executed 5 times. But when the program runs, you'll see that the finally block executes only 4 times. The 5th iteration will trigger the call of the Exit function, so this 5th time finally will never be triggered. The reason is that--system.exit suspends execution of all threads, including the current thread. Even if the finally block after the try statement is executed, the exit will be powerless.

When calling System.exit, the JVM performs two end tasks before shutting down:

First, it executes all the terminating hooks that are registered through Runtime.addshutdownhook. This is critical because it frees up resources outside the JVM.

The next is the finalizer. It could be system.runfinalizersonexit or runtime.runfinalizersonexit. The use of finalizer has been abandoned for a long time. Finalizer can be called on a surviving object, even if those objects are still being used by other threads. This can lead to unpredictable results and even deadlocks.

 Public classShutdownhooksdemo { Public Static voidMain (string[] args) { for(inti=0;i<5;i++)            {                    Final intFinal_i =i; Try{runtime.getruntime (). Addshutdownhook (NewThread () { Public voidrun () {if(final_i==4) {System.out.println ("Inside Try block.exiting without executing Finally Block."); System.exit (0);                    }                                            }                                            }); }                    finally{System.out.println ("Inside Finally Block."); }            }    }}
Five. Judging odd numbers

Look at these lines of code to see if they can be used to accurately determine if a number is odd.

 Public boolean oddornot (int  num) {    return num% 2 = = 1;}

It seems to be right, but each execution of four will have a wrong result (speak with the data). Considering the negative odd, it will not be 1 by dividing it by 2. Therefore, the return value is false, and this is not the case.

The code can be modified like this:

 Public boolean oddornot (int  num) {    return (num & 1)! = 0;}

This is not just a negative odd problem solved, and is fully optimized. Because arithmetic and logic operations are more efficient than multiplication operations, the results of calculations are faster.

Six. The difference between a single quote and a double quote
 Public class Haha {    publicstaticvoid  main (String args[]) {    System.out.print ("H" + "a");    System.out.print (' H ' + ' a ');}    }

It looks like this code will return "Haha", but the actual return is Ha169. The reason is that when double quotes are used, the characters are treated as strings, and if they are single quotes, the character values are converted to integer values through an operation called the underlying type widening. The values are then added together to get 169.

Seven. Some tips to prevent memory leaks

Memory leaks can result in degraded software performance. Because Java is automatically managing memory, developers don't have much to intervene with. However, there are some ways to prevent memory leaks.

    • Free database connections immediately after querying data
    • Use finally blocks whenever possible
    • Releasing an instance from a static variable
    • Avoid deadlocks

Deadlocks occur for a number of reasons. Avoiding deadlocks can be solved without a word. Typically, a synchronization object creates a deadlock when it waits for a lock on a resource owned by another synchronization object.

Try running the following program. It will tell you what a deadlock is. This deadlock is due to the fact that two threads are waiting for resources owned by each other, thus creating a deadlock. They will always wait, no one will let go first.

 Public classDeadlockdemo { Public StaticObject Addlock =NewObject ();  Public StaticObject Sublock =NewObject ();  Public Static voidMain (String args[]) {myadditionthread add=NewMyadditionthread (); Mysubtractionthread Sub=NewMysubtractionthread ();      Add.start ();   Sub.start (); }Private Static classMyadditionthreadextendsThread { Public voidrun () {synchronized(addlock) {intA = ten, B = 3; intc = A +b; System.out.println ("Addition Thread:" +c); System.out.println ("Holding First Lock ..."); Try{Thread.Sleep (10); }            Catch(Interruptedexception e) {} System.out.println ("Addition thread:waiting for Addlock ..."); synchronized(Sublock) {System.out.println ("Threads:holding Add and Sub Locks ..."); }         }      }   }   Private Static classMysubtractionthreadextendsThread { Public voidrun () {synchronized(sublock) {intA = ten, B = 3; intc = A-b; System.out.println ("Subtraction Thread:" +c); System.out.println ("Holding Second Lock ..."); Try{Thread.Sleep (10); }            Catch(Interruptedexception e) {} System.out.println ("Subtraction thread:waiting for Sublock ..."); synchronized(Addlock) {System.out.println ("Threads:holding Add and Sub Locks ..."); }         }      }   }}

Output:

Addition Thread:137 for addlock ... Subtraction  for sublock ...

But if the order of the calls changes, the deadlock problem is solved.

 Public classDeadlocksolutiondemo { Public StaticObject Addlock =NewObject ();  Public StaticObject Sublock =NewObject ();  Public Static voidMain (String args[]) {myadditionthread add=NewMyadditionthread (); Mysubtractionthread Sub=NewMysubtractionthread ();      Add.start ();   Sub.start (); }Private Static classMyadditionthreadextendsThread { Public voidrun () {synchronized(addlock) {intA = ten, B = 3; intc = A +b; System.out.println ("Addition Thread:" +c); System.out.println ("Holding First Lock ..."); Try{Thread.Sleep (10); }            Catch(Interruptedexception e) {} System.out.println ("Addition thread:waiting for Addlock ..."); synchronized(Sublock) {System.out.println ("Threads:holding Add and Sub Locks ..."); }         }      }   }   Private Static classMysubtractionthreadextendsThread { Public voidrun () {synchronized(addlock) {intA = ten, B = 3; intc = A-b; System.out.println ("Subtraction Thread:" +c); System.out.println ("Holding Second Lock ..."); Try{Thread.Sleep (10); }            Catch(Interruptedexception e) {} System.out.println ("Subtraction thread:waiting for Sublock ..."); synchronized(Sublock) {System.out.println ("Threads:holding Add and Sub Locks ..."); }         }      }   }}

Output:

Addition Thread:13for 7Holding Second Lock ... Subtraction  for  sublock ... Threads:holding Add and Sub Locks ...

Java issues to be aware of 1

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.