Java Engineer's written test set one

Source: Internet
Author: User

First, written questions:

1. Describe the difference between class and object, and the function of Java virtual function.

A class is an abstraction of an object that is a concrete instance of a class.
Classes are abstract, do not occupy memory, and objects are specific and occupy memory space.

Java does not have the concept of virtual functions, the normal function is equivalent to the virtual function in C + +, but can be in front of the function and final so that the function cannot be overridden. The function of a virtual function is to allow the redefinition of a function with the same name as the base class in a derived class, which is a manifestation of polymorphism.

2. Database table writes the SQL statement to remove duplicate records, preserving one of the lowest IDs.

Delete from TableName where ID not in (the Select min (ID) from tablename GROUP by Col1,col2,...)

3. Analyze the pros and cons of two for loops:

(1)

1  for (i=0; i<n; i++) 2       {3            if(condition)4                dosomething (); 5            Else 6                 dootherthing (); 7       }

(2)

1 if(condition)2       {3             for(i=0; i<n; i++)4 dosomething ();5       }6 Else7       {8             for(i=0; i<n; i++)9 dootherthing ();Ten}

Program (1) (former):
Advantages: Simple Procedure
The conditional judgment appears in the for, meaning that even if I change the value of condition in the 2 functions of dosomething () or dootherthing (), the For loop will execute my intention correctly, Because it will re-detect the value of Conditon in each cycle and do different actions for the value of condition, so-called status quo, this is commendable.
Disadvantage: More than the execution of N-1 logic judgment, and interrupted the cycle of "pipeline" operations, so that the compiler can not optimize the processing of the cycle, reducing efficiency.
If condition has never changed, our poor if must judge the true and false of condition every cycle. Sacrificing runtime efficiency.

Procedure (2) (latter):
Advantages: The efficiency of the cycle is high. Only one judgment is made and the operation is efficient. Suitable for situations where the value of the condition does not change.
Disadvantage: Since only one judgement is made at the beginning, the chance to change the value of condition is lost, that is, even if I change the value of condition in DoSomething () to False, the program will not change its judgment. It still carries out the cycle of dosomething (). We can't change the action we need at any time. This is the sacrifice of elasticity.

n larger, it is recommended to use the following writing, because the former to make logical judgments, interrupted the cycle of "pipeline" work, so that the compiler can not optimize the processing of the cycle, reducing efficiency.

4.1-100 of the natural number, put in the length of the array of 99 a[], design a good method, can easily find out the number of not put.

1 int total = 0; 2  for (int i=0; i<99; i++) {3total     + = A[i]; 4 }5 System.out.println ("Not put in number is:" + (5050-total));

Other methods:
1). Sort the 99 numbers in the array first, then binary the 1-100 numbers in the array in turn to find them in the Java
Arrays.binarysearch
2). In fact, if the array can be replaced by a set, you can directly determine whether the set of contain these 1-100 numbers can be
3). With HashMap implementation, the number 1-100 is put into the HashMap, key is a number, value casually, for example, for the 1,for loop traversal length 99 of the array, the HashMap remove the current number of key, the last remaining 1 number is the request.

5. Implement 100 with recursion!.

1 ImportJava.math.BigInteger;2 3  Public classFactorial {4 5      Public StaticBigInteger Callfactorial (intN) {6         if(N < 1)7             Throw Newillegalargumentexception ();8 9         if(n = = 1)Ten             returnBiginteger.one; One  A         returnCallfactorial (n-1). Multiply (biginteger.valueof (n)); -     } -  the      Public Static voidMain (string[] args) { - System.out.println (Callfactorial ()); -     } -}

6. Design mode: Singleton, Factory (code)

"Go" Java: Seven Ways to style a singleton

The first type (lazy, thread insecure):

1  Public classSingleton {2     Private StaticSingleton instance; 3   4      Public StaticSingleton getinstance () {5     if(Instance = =NULL) {  6Instance =NewSingleton (); 7     }  8     returninstance; 9     }  Ten}

This type of lazy loading is obvious, but the fatal is that the multithreading does not work properly.

The second type (lazy, thread safe):

1  Public classSingleton {2     Private StaticSingleton instance; 3   4      Public Static synchronizedSingleton getinstance () {5     if(Instance = =NULL) {  6Instance =NewSingleton (); 7     }  8     returninstance; 9     }  Ten}

This notation works well in multi-threading, and it seems to have a good lazy loading, but, unfortunately, is inefficient and does not require synchronization in 99% cases.

The third type (a Hungry man):

 1  public  class   Singleton { 2  private  static  Singleton instance = new    Singleton ();      3  4  public  static   Singleton getinstance () { 5  return   instance;  6  }  } 

This approach avoids multi-threaded synchronization problems based on the Classloder mechanism, however, instance is instantiated at class loading, although there are many reasons for class loading, most of which are called getinstance methods in singleton mode. However, it is not certain that there are other ways (or other static methods) that cause the class to load, when initializing instance obviously does not achieve the effect of lazy loading.

Fourth species (a Hungry man, variant):

1  Public classSingleton {2     PrivateSingleton instance =NULL; 3     Static {  4Instance =NewSingleton (); 5     }  6   7      Public StaticSingleton getinstance () {8     return  This. instance; 9     }  Ten}

The surface looks very different, in fact, the third Way is similar, all in class initialization is instantiated instance.

The fifth type (static inner Class):

1  Public classSingleton {2     Private Static classSingletonholder {3     Private Static FinalSingleton INSTANCE =NewSingleton (); 4     }  5   6      Public Static FinalSingleton getinstance () {7     returnsingletonholder.instance; 8     }  9}

This approach also takes advantage of the classloder mechanism to ensure that there is only one thread initialized instance, which differs from the third and fourth ways (very subtle differences): The third and fourth ways are as long as the Singleton class is loaded, Then instance will be instantiated (without the lazy loading effect), and this is singleton class is loaded, instance not necessarily initialized. Because the Singletonholder class is not actively used, the load Singletonholder class is displayed only if it is displayed by calling the GetInstance method, thus instantiating the instance. Imagine if instantiating instance is draining resources, I want him to delay loading, on the other hand, I don't want to instantiate when the singleton class loads, because I can't make sure that the Singleton class can be actively used in other places to be loaded, It is obviously inappropriate to instantiate instance at this time. At this point, this approach is reasonable compared to the third and fourth approaches.

The sixth type (enumeration):

1  Public enum Singleton {  2    INSTANCE;   3      Public void Whatevermethod () {  4    }  5

This approach is advocated by effective Java author Josh Bloch, which not only avoids multi-threaded synchronization problems, but also prevents deserialization from recreating new objects, which can be a very strong barrier, but Personally think that because of the 1.5 to join the enum characteristics, in this way to write inevitably people feel unfamiliar, in the actual work, I also rarely see someone write so.

Seventh type (double check lock):

1  Public classSingleton {2     Private volatile StaticSingleton Singleton; 3   4      Public StaticSingleton Getsingleton () {5     if(Singleton = =NULL) {  6         synchronized(Singleton.class) {  7         if(Singleton = =NULL) {  8Singleton =NewSingleton (); 9         }  Ten         }   One     }   A     returnSingleton;  -     }   -}

This is the second way of the upgrade version, commonly known as double check Lock, detailed information please see: http://www.ibm.com/developerworks/cn/java/j-dcl.html
After JDK1.5, the double-check lock is able to achieve a single-case effect normally.

Summarize
There are two issues to note:
1. If a singleton is loaded by a different class loader, there may be instances of multiple singleton classes. It is assumed that not remote access, such as some servlet containers, use a completely different class loader for each servlet, so that if there are two Servlets accessing a singleton class, they will have their own instance.
2. If the singleton implements the Java.io.Serializable interface, then instances of this class may be serialized and restored. In any case, if you serialize an object of a singleton class and then restore multiple objects, you will have multiple instances of the Singleton class.

The fix for the first problem is:

1 Private StaticClass getclass (String classname)2                                          throwsClassNotFoundException {3ClassLoader ClassLoader =Thread.CurrentThread (). Getcontextclassloader (); 4       5       if(ClassLoader = =NULL)     6ClassLoader = Singleton.class. getClassLoader (); 7       8       return(Classloader.loadclass (classname)); 9    }     Ten}

The fix for the second problem is:

1  Public classSingletonImplementsjava.io.Serializable {2     Public StaticSingleton INSTANCE =NewSingleton (); 3       4    protectedSingleton () {5         6    }     7    PrivateObject readresolve () {8             returnINSTANCE; 9       }    Ten}

For me, I prefer the third and fifth way, easy to understand, and thread-safe in the JVM layer (if not multiple classloader environments), in general, I will use the third way, only if you want to explicitly implement the lazy loading effect will be used in the fifth way, in addition, If it involves deserializing the creation of an object I will try to implement the singleton using enumerations, but I will always ensure that my program is thread safe, and I will never use the first and second way, if there are other special needs, I may use the seventh way, after all, JDK1.5 has no problem with double-check locking.

Factory mode: To be continued.

Java Engineer's written test set one

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.