20-Way Java interview required questions

Source: Internet
Author: User
Tags repetition set set throwable

The system has organized a bit of questions about Java, including Basic, Javaweb, frame, database, multi-threaded, concurrent articles, algorithms and so on, updated in succession. Other aspects such as the front end and so on the face of the questions are also in the collation, there will be.

Note: At the end of the article there are benefits! PDF version can be obtained at the end of the article

1. The difference between ArrayList and vectors

These two classes all implement the list interface (the list interface inherits the collection interface), they are all ordered collections, that is, the location of the elements stored in these two collections are sequential, equivalent to a dynamic array, we can later by the location index number to take out an element, And the data in it is allowed to be duplicated, which is the largest difference from a collection such as HashSet, and a collection such as HashSet cannot retrieve its elements by index number, nor does it allow duplicate elements.

The difference between ArrayList and Vector mainly consists of two aspects:.
(1) synchronization:

The vector is thread-safe, that is, it is thread-synchronized between its methods, and ArrayList is a thread-less program that is not synchronized between its methods. If there is only one thread routines access to the collection, it is best to use ArrayList, because it is more efficient than thread-safe, and if there are multiple lines routines access to the collection, it is best to use vectors, since we do not need to consider and write thread-safe code ourselves.

(2) Data growth:

ArrayList and Vector have an initial capacity size, when the number of elements stored in them exceeds the capacity, you need to increase the storage space of ArrayList and vector, each time to increase storage space, not only add a storage unit, but add multiple storage units, Each increase in the number of storage units in memory space utilization and program efficiency to achieve a certain balance. Vector growth is twice times the default, and ArrayList's growth strategy is not clearly defined in the documentation (from the source code to see the growth of 1.5 times times the original). Both the ArrayList and vector can set the initial space size, and the vector can also set the amount of space to grow, while ArrayList does not provide a way to set the growth space.

Summary: That is, the vector increases the original one times, the ArrayList increases the original 0.5 times times.

2. The difference between HashMap and Hashtable

HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation), they all complete the map interface, the main difference is that the HASHMAP allows null (NULL) key value (key), because of non-thread security, in the case of only one thread access, More efficient than Hashtable.

HashMap allows NULL to be used as a entry key or value, and Hashtable is not allowed.

HashMap hashtable contains method removed, changed to Containsvalue and ContainsKey. Because the contains method is easy to cause misunderstanding.

Hashtable inherits from the dictionary class, and HashMap is an implementation of the map interface introduced by Java1.2.

The biggest difference is that the Hashtable method is synchronize, and HashMap is not, when multiple threads access Hashtable, they do not need to synchronize their methods, and HashMap must provide synchronization.

HashMap and Hashtable are mainly from three aspects.
I. Historical reasons: Hashtable is based on the old dictionary class, HashMap is an implementation of the map interface introduced by Java 1.2
Two. Synchronization: Hashtable is thread-safe, that is, synchronous, and HashMap is a thread program is not secure, not synchronous
Three. Value: Only HashMap can let you use NULL as the key or value of an entry for a table

3. What is the difference between list and map?

One is a collection of single-column data, and the other is a collection of two columns of data such as keys and values, and the data stored in the list is sequential and repeatable; the data stored in the map is not sequential, its keys cannot be duplicated, and its values can be duplicated.

4. List,set, does the map inherit from the collection interface?

List,set Yes, map is not

5, List, MAP, set three interfaces, access to elements, what are the characteristics of each?

(Such a question comparative test level, two aspects of the level: first, to really understand these content, the second is to have a strong summary and presentation ability. )

First, the list and set have similarities, both of which are collections of single-column elements, so they have a common parent interface called collection. Duplicate elements are not allowed in the set, that is, there cannot be two equal (note, not just the same) object, that is, assuming that the set set has an A object, and now I want to deposit a B object to the set set, but the B object is equal to equals of the A object, the B object is not stored in, so The Add method of the Set collection has a Boolean return value, when there is no element in the collection, when the Add method can successfully join the element, returns True when the collection contains an element equal to the equals of an element, the Add method cannot join the element, and the return result is false. When set takes an element, it is not necessary to take the first few points, only to get all the elements in the iterator interface, and then iterate through each element individually.

The list indicates a sequential collection, noting that it is not sort by age, by size, by price, and so on. When we call the Add (Obje) method multiple times, each time the object is added is like a train station to buy tickets in a queued order, sorted by first served order. Sometimes, you can also jump in the queue, called the Add (Intindex,obj e) method, and you can specify where the current object is stored in the collection. An object can be repeatedly stored in the list, each call to the Add method, the object is inserted into the collection once, in fact, not the object itself is stored in the collection, but in the collection with an index variable point to the object, when the object is add multiple times, That is, there are multiple indexes in the collection pointing to this object, as shown in X. In addition to using the iterator interface to get all the elements, and then iterate through each element, you can also call get (index i) to clarify the number of the first.

Unlike list and set, map is a set of two columns, with the Put method defined as follows: Put (obj key,obj value), each time it is stored, to store a pair of key/value, cannot store duplicate key, this repeating rule is equal to equals. You can obtain the corresponding value according to key, which is the value that the get (Object key) returns to key. In addition, you can get all the key combinations, you can also get all the value of the union, you can also get a combination of key and value of the Map.entry object collection.

Lists hold elements in a particular order, and can have repeating elements. Set cannot have duplicate elements, internal ordering. Map holds the Key-value value, and value can be multivalued.

6, say the arraylist,vector,linkedlist storage performance and characteristics

Both ArrayList and vectors use arrays to store data, which is larger than the actual stored data in order to add and insert elements, both of which allow the element to be indexed directly by ordinal, but the insertion element involves memory operations such as array element movement, so the index data is fast and the data is inserted slowly. Vector due to the use of the Synchronized method (thread-safe), usually performance is worse than ArrayList. While LinkedList uses a doubly linked list for storage, indexing data by ordinal requires a forward or backward traversal, and the index slows down, but inserting the data requires only the front and back of the item to be recorded, so the insertion is faster.

LinkedList is also thread insecure, LinkedList provides methods that enable LinkedList to be used as stacks and queues.

7. Remove duplicate elements from a vector set

New Vector (); for (int i=0;i<vector.size (); i++= vector.get (i);        if (! newvector.contains (obj);             Newvector.add (obj);}

There is also an easy way to take advantage of the Set does not allow repeating elements:

New HashSet (vector);

8. The difference between collection and collections.

Collection is the ancestor interface of the collection class, and inherits his interface mainly set and list.

Collections is a helper class for a collection class that provides a series of static methods for searching, sorting, threading, and so on for various collections.

9, the set of elements can not be repeated, then what method to distinguish between repetition or not? = = or equals ()? What is the difference between them?

The elements in the set cannot be duplicated, and the repetition of the elements is judged using the Equals () method.

= = and equal difference is also a bad question, here say:

The = = operator is specifically used to compare the values of two variables, that is, whether the value stored in the memory used to compare the variables is the same, to compare two basic types of data or two reference variables equal, only with the = = operator.

The Equals method is used to compare the contents of two separate objects, as compared to two people whose looks are the same, compared to the two objects that are independent of each other.

For example: Two new statements create two objects, and then use a/b to point to one of the objects, which is two different objects, their first address is different, that is, the values stored in a and B are not the same, so the expression a==b will return False, The contents of the two objects are the same, so the expression a.equals (b) returns True.


10, what are the collection classes you know? The Main method?

The most common collection classes are List and Map. The specific implementation of the list includes ArrayList and vectors, which are variable-sized lists that are more appropriate for building, storing, and manipulating any type of object. List is useful for cases where elements are accessed by numeric indexes.

MAP provides a more general method of storing elements. The Map collection class is used to store element pairs (called "Keys" and "values"), where each key is mapped to a value.

They all have the method of increasing the pruning and checking.

For set, the approximate method is Add,remove, contains, etc.

For map, the approximate method is put,remove,contains, etc.

The list class will have a method such as get (int index), because it can take elements sequentially, and the set class does not have a method such as get (int index). Both the list and the set can iterate over all the elements, and the set and list classes have a iterator method for returning the iterator object before iterating to get a iterator object. Map can return three sets, one is to return all the keys of the collection, the other one returns a collection of all values, and then a return key and value combined into the EntrySet object collection, Map has a Get method, the parameter is key, The return value is a key corresponding to the value, this free play, nor the ability to test methods, these programming process will be prompted, combined with the differences between the three of them to say the use of the line.

1 1. String s = new string ("xyz"); how many stringobject have been created? Can I inherit the string class?

Two or one is possible, "XYZ" corresponds to an object, the object is placed in a string constant buffer, and the constant "XYZ" is the one in the buffer, no matter how many times it occurs. Newstring Creates a new object each time it is written , using the contents of the constant "xyz" object to create a new string object. If ' xyz ' had been used before, then "XYZ" would not have been created and would have been taken directly from the buffer, when a stringobject was created, but if "XYZ" had not been used before, then an object was created and put into the buffer, in which case it created two objects. As to whether the string class inherits, the answer is no, because the string default final decoration is not inheritable .

1 2. The difference between string and StringBuffer

The Java platform provides two classes: string and StringBuffer, which can store and manipulate strings, which are character data that contain multiple characters. This string class provides a string of values that cannot be changed. The string provided by this StringBuffer class can be modified. You can use StringBuffer when you know that character data is going to change. Typically, you can use Stringbuffers to dynamically construct character data.

1 3. The following statement creates a total of how many objects: String s= "a" + "B" + "C" + "D";

For the following code:

String S1 = "a"= s1 + "B"= "a" + "B"= = "AB" = = "AB");

The first statement prints the result of false, the second statement prints a true result, which means that the Javac compilation can be optimized for the expression that adds the string constants directly, without having to wait until the run time to do the addition processing, but to remove the plus sign at compile time. Compiles it directly into a result that these constants are connected to.

The first line of code in the title is optimized by the compiler at compile time, which is equivalent to a string that directly defines an "ABCD", so the above code should only create a string object. Write the following two lines of code,

String s = "a" + "B" + "C" + "D"; System.out.println (s= = "ABCD");

The result of the final printing should be true.

1 5, final, finally, finalize the difference.

Final is used to declare properties, methods, and classes, respectively, that the property is immutable, that the method is not overridden, and that the class is not inheritable. Internal classes to access local variables, local variables must be defined as final types.

Finally is part of the exception-handling statement structure, which indicates that it is always executed.

Finalize is a method of the object class that, when executed by the garbage collector, calls this method of the reclaimed object, and can override this method to provide garbage collection of other resource recycles, such as closing the file. However, the JVM does not guarantee that this method is always called

1 6. What are the similarities and differences between abnormal operation and general anomaly?

An exception represents an unhealthy state that may occur during a program's run, and a run-time exception that represents an exception that may be encountered in a typical operation of a virtual machine is a common run error. The Java compiler requires the method to declare a non-runtime exception that might occur, but does not require that a runtime exception that is not caught to be thrown must be declared.

1 7. What is the difference between error and exception?

Error indicates a serious problem in situations where recovery is not impossible but difficult. For example, memory overflow. It is impossible to expect the program to handle such situations. Exception represents a design or implementation issue. That is, it means that if the program runs normally, it never happens.

1 8. Simply talk about the simple principle and application of exception handling mechanism in Java.

Exceptions are abnormal conditions or errors that occur when a Java program is run (not compiled), similar to real-life events, where real-life events can contain information about the time, place, people, and plot of an event, which can be represented by an object, and Java uses an object-oriented approach to handling exceptions. It encapsulates each exception that occurs in the program into an object that contains information about the exception.

Java classifies exceptions, different types of exceptions are represented by different Java classes, and the root class for all exceptions is java.lang.throwable,throwable with two sub-classes derived below:

Error and Exception,error represent a serious problem that the application itself cannot overcome and recover, and the program only crashes, for example, a system problem such as memory overflow and thread deadlock.

Exception indicates that the program can also overcome and recover problems, which are divided into system exceptions and common exceptions:

System anomaly is the problem caused by the defects of software itself, which is caused by the poor consideration of software developers, and software users cannot overcome and recover the problem, but in this case the software system can continue to run or let the software hang out, for example, Array script out of bounds (arrayindexoutofboundsexception), null pointer exception (NULLPOINTEREXCEPTION), class conversion exception (classcastexception);

Ordinary exception is the operating environment changes or anomalies caused by the problem, is the user can overcome problems, such as network disconnection, hard disk space is not enough, after such an exception, the program should not die.

Java provides a different solution for system exceptions and common exceptions, and the compiler enforces common exceptions that must try: Catch processing or using the throws declaration continues to be thrown to the upper call method processing, so the common exception is also called the checked exception, and the system exception can be handled or not handled, so the compiler does not enforce with try. catch processing or declaration with throws, so system exceptions are also known as unchecked exceptions.

1 9. What is the difference between heap and stack in Java?
The heap and stack in the JVM belong to different memory regions and are used for different purposes. Stacks are often used to save method frames and local variables, and objects are always allocated on the heap. Stacks are usually smaller than heaps and are not shared across multiple threads, and the heap is shared by all threads of the entire JVM.

Stacks: Some of the basic types of variables defined in the function and the reference variables of the objects are allocated in the stack memory of the function, and when a variable is defined in a block of code, Java allocates the memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated for that variable. The memory space can be used immediately by another.

Heap: Heap memory is used to store the objects and arrays created by new, and the memory allocated in the heap is managed by the automatic garbage collector of the Java virtual machine. After creating an array or an object in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object. The reference variable in the stack can then be used in the program to access an array or an object in the heap, which is equivalent to a name that is an array or an object.

2 0. Can i cast int to a variable of type byte? What happens if the value is greater than the range of type byte?
We can do the cast, but the int in Java is 32 bits, and byte is 8 bits, so if you force conversions, the high 24 bits of the int type will be discarded because the byte type range is from-128 to 127.

Follow the public number reply to the Java question to get the PDF version!

A conscience public number "IT resources":

This public number is committed to free sharing of the best video resources, learning materials, interview experience, Front end, Php,java, algorithms, Python, big Data and so on, which you want to have

IT Resources-QQ Exchange Group: 625494093

Can also add pull you into the group: super1319164238

Search public Number: Itziyuanshe or scan the QR code below direct attention,

20-Way Java interview required questions

Related Article

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.