Java interview questions featured three

1, compare the Java and JavaSciprt.
Answer: JavaScript and Java are two developed two different products. Java is a former Sun Microsystems has introduced object-oriented programming language, particularly suitable for Internet application development; and JavaScript is Netscape's products Netscape browser in order to expand the development of a function can be embedded in Web pages running Object-based and event-driven interpretive language. JavaScript is the predecessor LiveScript; and the Java language, formerly known as Oak.
Next, the similarities and differences between the two languages to make the following comparison:

  • Object-based and object-oriented: Java is a true object-oriented language, even the development of simple procedures, you must design objects; JavaScript is kind of scripting language that can be used to make the network independent, user interaction with complex software. It is an object (Object-Based) based and event-driven (Event-Driven) programming language, which itself provides a very rich internal object for designers to use.
  • Interpretation and compilation: Java source code before execution, must be compiled. JavaScript is an interpreted programming language, its source code need not compiled, interpreted by the browser execution. (Almost all browsers currently use the JIT (time compiler) technology to enhance the operating efficiency of JavaScript)
  • Strongly typed variables and types of weak variables: Java strongly typed variable checking that all variables before compiling must make a statement; JavaScript variables are weakly typed, even before the use of variables can silence Ming, JavaScript interpreter checks at run time inferred data type.
  • Code format is not the same.

Added: four points listed above are circulated on the Internet so-called standard answer. In fact, Java and JavaScript the most important difference is that a static language, is a dynamic language. Current trends programming language is a functional and dynamic languages. In Java class (class) is a first-class citizen in the JavaScript function (function) is a first-class citizen, so JavaScript programming support function, and may function using a Lambda closure (closure), of course, have begun to support Java. 8 functional program, provides support for Lambda expressions and functional interface. For such problems, during the interview is best answered in their own language will be more tricky, not the so-called standard answer back online.

2, when to use assertions (assert)?
A: Yes execution, execution before returning to the caller method.

3, how the Java language exception handling, keyword: throws, throw, try, catch , finally , respectively, how to use?
A: Java exception handling through object-oriented approach, to classify the various anomalies, and provides a good interface. In Java, each anomaly is an object that is an instance of the class Throwable or subclass. When a method throws an exception occurs after exception object, the object method contains exception information, call this object can capture the exception and can process it. Java exception handling is achieved through five keywords: try, catch, throw, throws, and finally. Is generally try to execute a program, if the system will throw (the throw) an exception object may be captured (the catch) which by its type, or by always executing code block (the finally) treated; try with all exceptions to specify a prevention program; catch clause immediately after the try block, is used to specify the type of exception you want to capture; throw statement to explicitly throw an exception; throws to declare a method might throw a variety of abnormalities (of course declare an exception allowing the fuss); finally a piece of code to ensure that no matter what strange happened must be carried out; try statements can be nested, whenever it encounters a try statement, an abnormal structure will be put the exception stack until all try statements are completed. If you try the next level of some kind of statement does not deal with exceptions, exception stack pop operations will be executed until it has to deal with this anomaly encountered try statement or final exception thrown JVM.

3. What is the run-time exceptions and abnormal subjects similarities and differences?
A: The abnormality shows an abnormal state program is running that may arise abnormality shows runtime exceptions usually a virtual machine that may be encountered, is a common run-time error, as long as the programming was no problem usually does not occur. Subjects with abnormal context running about, even if the programming is correct, because the problem may still be used and thrown. Java compiler must request a declaration throws subjects abnormalities may occur, but is not required when running throw uncaught exceptions must be declared. Abnormalities and inherited, is object-oriented programming in what is often abused in Effective Java in the use of the exception gives the following guidelines:

  • Do not use exception handling for normal control flow (well-designed API should not be forced to its caller to control the flow of normal and abnormal use)
  • Use subjects abnormal situation can be restored, an exception to the use of run-time programming errors
  • Subject to avoid unnecessary use of the exception (through some state detecting means to prevent the occurrence of abnormality)
  • Priority use of standard exceptions
  • Each method throws an exception must have documentation
  • Abnormality atomicity
  • Do not ignore caught exception in the catch

4, list some of your common runtime exception?
answer:

  • ArithmeticException (arithmetic exception)
  • A ClassCastException (class cast exception)
  • IllegalArgumentException (illegal argument exception)
  • IndexOutOfBoundsException (subscript bounds exception)
  • A NullPointerException (null pointer exception)
  • SecurityException (Security Exception)

5, explained the difference between final, finally, finalize the.
answer:

  • final: modifier (keyword) There are three usage: if a class is declared final, meaning that it can not send another unexpected new sub-class that can not be inherited, so it is abstract and antonyms. The variable declared as final, can guarantee that they are not in use change, it is declared as final variables must be given in the initial statement, and in subsequent references can only read can not be modified. It declared final approach also only use, can not be overridden in a subclass.
  • finally: the code is usually placed behind the try ... catch ... always execute the code block structure, which means that the program regardless of normal or abnormal execution occurs, the code does not close here as long as the JVM can execute, you can write in the release of external resources finally block.
  • finalize: Object methods defined in the class, Java allowed to use finalize () method to remove the object to do the necessary clean-up work before going out from memory in the garbage collector. This method is called by the garbage collector when the object is destroyed, you can tidy up system resources by overriding the finalize () method or perform other cleanup work.

6, class ExampleA inherit Exception, class ExampleB inherit ExampleA.
The following code fragment:

try {
    throw new ExampleB("b")
} catch(ExampleA e){
    System.out.println("ExampleA");
} catch(Exception e){
    System.out.println("Exception");
}

Ask what the output of this code is executed?
A: Output: ExampleA. (According to Richter substitution principle [supertype can be used where a certain subtypes can be used], ExampleA grab type of anomaly can grasp ExampleB catch block try block type of exception thrown)

Interview questions - say the operation of the following code. (The source of this problem is to "Java programming ideas" a book)

class Annoyance extends Exception {}
class Sneeze extends Annoyance {}

class Human {

    public static void main(String[] args) 
        throws Exception {
        try {
            try {
                throw new Sneeze();
            } 
            catch ( Annoyance a ) {
                System.out.println("Caught Annoyance");
                throw a;
            }
        } 
        catch ( Sneeze s ) {
            System.out.println("Caught Sneeze");
            return ;
        }
        finally {
            System.out.println("Hello World!");
        }
    }
}

answer:

Annoyance Caught
Caught Sneeze
the Hello World!
I believe the first and third rows we have no doubt, the key is the second line, it should be out of it? Is not a subclass of catch that exception parent do?
After adding breakpoints, we found that although
catch (Annoyance a)
This sentence is a reference to the use of the parent class, but is actually a subclass of the object, which is a classic manifestation of java polymorphism. In the
catch (Sneeze s)
when the course can capture their own thrown out the anomaly.

7, List, Set, Map whether inherited from the Collection interface?
A: List, Set Shi, Map not. Map key-value mapping containers, and Set List with a clear distinction, the fragmented and stored Set of elements does not permit duplicates (mathematics set too), the container is a linear structure List for-value index case access elements.
Here Insert Picture Description
8, set forth ArrayList, Vector, LinkedList storage performance and characteristics.
A: ArrayList and Vector data is stored using an array, the array element number is greater than the actual data is stored so as to increase and insert elements, which allow the element directly indexed by serial number, but to insert the element array elements involved in memory operations like move, so index data fast and slow insert data, methods of Vector are modified by the addition of synchronized, so Vector is thread-safe container, but the poor performance than ArrayList, and therefore has a legacy container in Java. LinkedList implemented using a doubly linked list is stored (in the memory by the associated reference memory cell scattered added together to form a linear structure can be indexed by serial number, which compared to a continuous chain storage array storage, memory utilization higher), indexed by serial number before the data needs to traverse to or after, but only before and after the record of this can insert the data item, the insertion speed. Vector belong legacy container (container earlier versions of Java provided in addition, Hashtable, Dictionary, BitSet, Stack , Properties are the legacy container), is no longer recommended, but due to the ArrayList and LinkedListed are non-thread-safe, If the scene with a container of experience operating multiple threads, you can synchronizedList methodological tools category Collections will convert it into thread-safe container before use (this is the application for decorating mode, existing objects will pass another the constructor of a class of objects to create a new enhancement implementation).

NOTE: Properties class vessel left and Stack classes have serious problems in the design, Properties is a special key and key values ​​are mapped string, the design should be associated with one and two which Hashtable generic type parameter is set to String, but in the Java API Properties directly inherited Hashtable, which obviously is the inheritance of abuse. Here multiplexing mode code should Has-A relationship instead of Is-A relationship, on the other hand containers are all tools, tools inherited class itself is a wrong approach, the best way to use tools is Has-A relationship (association) or Use-A relationship (dependency). Similarly, Stack class extends Vector is also incorrect. Sun's engineers have also made such a stupid mistake, people marvel.

9, Collection and Collections of the difference?
A: Collection is an interface, it is the parent interface Set, List and other containers; Collections is a utility class that provides a series of static methods to assist container operations, these methods include searching for containers, sorting, thread safety etc. Wait.

10, List, Map, Set three interfaces while the access elements, what are the differences?
A: List a particular index accesses elements, there may be duplicate elements. Set not store duplicate elements (with the object equals () method to distinguish whether to repeat elements). Map save key-value pair (key-value pair) mapping, mapping relationship can be one or many. When the container has Set Map implementation version based on two hash tree storage and sorting access time complexity is O (1) based on the theoretical version stored hash, the version of the tree sort Based insert or delete elements would constitute a sort tree in accordance with the key element or elements (key) and to re-ordering to achieve the effect.

Published 444 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/zt2650693774/article/details/105022804