Java Interview--4

Source: Internet
Author: User
Tags finally block instance method reflection thread class visibility volatile

This article will be frequently encountered in the interview of Java Technology Point of a comprehensive in-depth summary, help us in the interview more handy, not to participate in the interview students can also take this opportunity to comb their knowledge system, to check the leakage of the vacancy (read this article needs to have a certain Java foundation; If you start with Java, These questions can be used to establish a preliminary impression of Java, after a certain basis and then look at the harvest will be greater). The list of questions in this article is from http://www.nowcoder.com/discuss/3043, thanks to the original author's selfless sharing:)

1. What are the original data types in Java, and what are their sizes and corresponding encapsulation classes?

(1) Boolean

The Boolean data type is False if it is not true. This data type represents 1 bit of information, but its size is not precisely defined.

In the Java Virtual Machine specification, it says, "although the data type of Boolean is defined, it only provides very limited support." In a Java virtual machine, there are no bytecode directives dedicated to Boolean values, and the Boolean values that are manipulated by the Java language expression are replaced with the int data type from the Java Virtual machine after compilation. The Boolean array is encoded as a byte array of the Java virtual machine, with each element having a Boolean element of 8 bits. This way we can conclude that the boolean type is 4 bytes alone and 1 bytes in the array. Why does the virtual machine use int instead of Boolean? Why not use a byte or short, so it's not more memory-saving space? In fact, the reason for using int is that for the current 32-bit CPU, a 32-bit data exchange is more efficient at once.

In summary, we can know: The official document does not give the exact definition of the Boolean type, the Java Virtual Machine specification gives the definition of "use 4 bytes, 1 bytes in a Boolean array", and depends on whether the virtual machine implementation follows the specification, so 1 bytes, It is possible to have 4 bytes. This is actually a time-space tradeoff.

The wrapper class for the Boolean type is Boolean.

(2) Byte--1 Byte--byte

(3) Short--2 Bytes--short

(4) Int--4 Bytes--integer

(5) Long--8 Bytes--long

(6) Float--4 Bytes--float

(7) Double--8 bytes--double

(8) Char--2 Bytes--character

2. Talk about the difference between "= =" and "Equals ()".

Think in Java says: "Relational operators generate a Boolean result that calculates the relationship between the operands ' values."

the "= =" Determines whether the memory address of the two objects is the same, applies to the original data type and enumeration type (their variables store the value itself, and the reference type variable stores the reference); equals is the method of the object class, and object implements it by comparing the memory address. We can override this method to customize the concept of "equality". Classes such as String, date, and so on in a class library override this method.

In summary, you should use "= =" for equality comparisons between enum types and raw data types, and you should use the Equals method for equality comparisons of reference types.

3. What are the four types of references in Java and their application scenarios?
    • Strong references: Usually we use the new operator to create an object that returns a reference that is a strong reference

    • Soft reference: If an object can only be reached through a soft reference, then this object will be recycled when it is not in sufficient memory, can be used in the picture cache, the system will automatically reclaim the unused bitmap

    • Weak reference: If an object can only be reached through a weak reference, then it will be recycled (even if memory is sufficient), it can also be used in the image cache, as long as the bitmap no longer used will be recycled

    • Virtual Reference: A virtual reference is the most "weak" reference in Java, and through it cannot even get the referenced object, the only thing that exists is that when the object it points to is recycled, it itself is added to the reference queue, so that we can know when the object it points to is destroyed.

4. What are the methods defined in object?

Clone (), Equals (), Hashcode (), toString (), notify (), Notifyall (), Wait (), Finalize (), GetClass ()

5. What is the role of hashcode?

See the basic principle and implementation of hash table

6. What is the difference between ArrayList, linkedlist and vectors?
    • ArrayList: Internal use of array storage elements, support efficient random access, support dynamic sizing

    • LinkedList: Internal use of linked lists to store elements, support for fast insertion/deletion of elements, but do not support efficient random access

    • Vector: Can be viewed as a thread-safe version of ArrayList

7. String, StringBuilder, what is the difference between stringbuffer?
    • String: Immutable character sequence to add new characters to it requires a new string object to be created

    • StringBuilder: variable character sequence that supports adding new characters to it (without creating a new object)

    • StringBuffer: Can be viewed as a thread-safe version of StringBuilder

8. Features and usage of MAP, Set, List, Queue, stack.
    • map<k, v>: The data type that stores key-value pairs in Java implements this interface, which represents the "Map table." The two core operations supported are get (Object key) and put (K key, V value), which are used to get the value corresponding to the key and insert a key-value pair into the mapping table.

    • set<e>: Duplicate elements are not allowed in a collection type that implements this interface, and represents a "set" in mathematical sense. The core operations it supports are Add (e E), Remove (Object o), contains (object o), which are used to add elements, delete elements, and determine whether a given element exists in the set.

    • list<e>: The list type in the collection framework in Java implements this interface, which represents an ordered sequence. Support for operations such as get (int index), Add (e e) .

    • queue<e>: The queue interface in the Java Collection Framework, which represents the FIFO queue. Support for operations such as Add (E Element), Remove () .

    • Stack<e>: The Java collection framework represents the data type of the stack, which is a "last in, first out" data structure. Support for operations such as push (E Item), pop () .

For more detailed instructions, please refer to the official documentation and the students who are unfamiliar with the relevant data structures can refer to the introduction to algorithms or other related books.

9. The difference between HashMap and Hashtable
    • Hashtable is thread-safe, and HashMap is not

    • Null keys and Null values are allowed in HashMap, but not allowed in Hashtable

For more detailed analysis, please refer to in-depth parsing hashmap, HashTable

the implementation principle of HashMap

Simply put, HashMap's bottom-up implementation is "a hash table based on the Zipper method". For detailed analysis, please refer to in-depth parsing hashmap, HashTable

The realization principle of concurrenthashmap

Concurrenthashmap is a support for concurrent read and write HashMap, which is characterized by the need to read data without locking, write data can ensure that the lock granularity as small as possible. Because of its internal use of "segmented storage", only the "segment" of the data to be written is locked. For a detailed analysis of the concurrenthashmap underlying implementation, refer to Java Concurrency Programming: concurrenthashmap of concurrent containers

What is the difference between TreeMap, Linkedhashmap and HashMap?
    • The underlying implementation of HASHMAP is a hash table, so the elements stored inside it are unordered;

    • The underlying implementation of the TREEMAP is a red-black tree, so it has an orderly inner element. The sort is based on the natural order or the comparer (Comparator) object that is provided when the TreeMap is created.

    • Linkedhashmap can remember the order in which elements are inserted.

For more detailed instructions please refer to the difference of Hashmap,linkedmap,treemap

What is the difference between collection and collections?

collection<e> is the basic interface in the Java Collection framework, and collections is a tool class provided by the Java Collection framework that contains a number of static methods for manipulating or returning a collection.

For small partners who are not familiar with the Java Collection framework, refer to the collection framework of the Java Core Technology point

14. For "try-catch-finally", if the Try statement block contains a "return" statement, will the finally statement block execute?

The answer is to be executed. In only two cases, the statements in the finally block will not be executed:

    • Called the System.exit () method;

    • The JVM has "crashed".

the exception hierarchy in Java

The exception hierarchy in Java is as follows:

We can see that the Throwable class is the base class in the exception hierarchy. The error class represents an internal error that is beyond our control; exception represents an exception, RuntimeException and its subclasses belong to an unchecked exception, such exceptions include ArrayIndexOutOfBoundsException, NullPointerException, we should avoid the occurrence of unchecked anomalies by means of conditional judgment and so on. IOException and its subclasses are checked exceptions, and the compiler checks to see if we provide an exception handler for all the checked exceptions that might be thrown, and if not, an error. For unchecked exceptions, we don't need to capture (and of course Java also allows us to capture, but what we should do to avoid unchecked exceptions).

three features and meanings of Java-oriented objects

Three major characteristics: encapsulation, inheritance, polymorphism. Read more about Poke Java object-oriented three major features

overload. Override, meaning and difference
    • Override means "override", which is the redefinition of the same method in the parent class by the child class

    • Overload means "overloaded," which means defining a new method with the same name as the defined method, but with a different signature

18. The difference between an interface and an abstract class

An interface is a convention in which classes that implement an interface follow this Convention; Abstract classes are inherently a class, and the cost of using an abstract class is larger than the interface. The comparison between the interface and the abstract class is as follows:

    • An abstract class can contain attributes, methods (containing abstract methods and methods with concrete implementations), constants, and interfaces can only contain constants and method declarations.

    • Methods and member variables in an abstract class can define visibility (such as public, private, and so on), whereas methods in an interface are public only (the default is public).

    • A subclass can have only one parent class (a specific class or abstract class), and an interface may inherit one or more interfaces, and a class can implement multiple interfaces.

    • When you implement an abstract method in a parent class in a subclass, the visibility can be greater than or equal to the parent class, whereas the interface method in an interface implementation class can only have the same visibility as the interface (public).

19. The difference between static inner class and non-static inner class

Static inner classes do not hold references to peripheral classes, and non-static inner classes implicitly hold a reference to the perimeter class.

To learn more about inner classes, poke inside the Java Core technology point class

the implementation principle of polymorphism in Java

The so-called polymorphic refers to the parent class reference to the subclass object, which invokes the implementation of the subclass rather than the implementation of the parent class. The key to polymorphic implementations is "dynamic binding." Detailed introduction to the internal implementation mechanism of Java dynamic binding

21. Describe two methods of creating new threads in Java
    • Inherit the thread class (assuming that the subclass is Mythread), rewrite the Run () method, and then new a Mythread object and call Start () to start it.

    • Implement the Runnable interface (assuming the implementation class is myrunnable), and then pass the Myrunnable object as a parameter to the thread constructor and invoke the start () method on the resulting thread object.

22. A brief description of thread synchronization methods in Java
    • The Volatile:java Memory model guarantees The write happens of the same volatile variable before read it;

    • Synchronized: can be used to lock a block of code or a method, "locked" in the place called the critical section, the thread entering the critical section will get the object's monitor, so that other attempts to enter the critical section of the thread will be blocked because the monitor can not be obtained. A thread that is blocked waiting for another thread to release monitor cannot be interrupted.

    • Reentrantlock: The thread attempting to acquire the lock can be interrupted and the timeout parameter can be set.

For a more detailed introduction, poke the Java core Technology point to multi-threading

23. Briefly describe what kinds of locks are in Java

In Java, you can lock classes, objects, methods, or blocks of code. For a more detailed introduction, poke the Java core Technology point to multi-threading

24. A solution to the problem of "producer-consumer"

to use a blocking queue:

public class Blockingqueuetest {private int size = 20;         Private arrayblockingqueue<integer> Blockingqueue = new arrayblockingqueue<> (size);        public static void Main (string[] args) {blockingqueuetest test = new Blockingqueuetest ();        Producer Producer = Test.new Producer ();                 Consumer Consumer = Test.new Consumer ();        Producer.start ();    Consumer.start ();                } class Consumer extends thread{@Override public void Run () {while (true) {                    try {//Remove an element from a blocking queue queue.take ();                System.out.println ("queue remainder" + queue.size () + "elements"); } catch (Interruptedexception e) {}}}} class Producer E                    Xtends thread{@Override public void Run () {while (true) {try { Inserts an element into a blocking queue QueuE.put (1);                System.out.println ("Queue remaining space:" + (Size-queue.size ())); } catch (Interruptedexception e) {}}}}}

Design concept and role of threadlocal

The role of threadlocal is to provide local variables within the thread, which ensures that the threadlocal variables within each thread are independent when accessed in a multithreaded environment. That is, each thread's threadlocal variable is private, and other threads are inaccessible. Threadlocal is most commonly used in this scenario where there is concurrent access to non-thread-safe objects in a multithreaded environment, and that the object does not need to be shared between threads, but we do not want to lock it, then use threadlocal to allow each thread to hold a copy of the object.

Analysis of the implementation principle of threadlocal please poke in-depth analysis threadlocal

The overall architecture of the concurrent package

Arrayblockingqueue, the role of the Countdownlatch class
    • Countdownlatch: Allows the thread set to wait until the counter is 0. Scenario: When one or more threads need to wait for a specified number of events to occur before continuing execution.

    • Arrayblockingqueue: A blocking queue based on an array implementation that needs to specify capacity at construction time. The current thread is blocked when an attempt is made to add an element to the full queue or to remove an element from an empty queue. By blocking the queue, we can work in the following pattern: worker threads can periodically put intermediate results in a blocking queue, and other threads can take out intermediate results and do further operations. If a worker thread executes slowly (before it can insert an element into the queue), other threads that take elements from the queue wait for it (attempting to take an element from the empty queue to block), and if the worker thread executes faster (attempting to insert an element into the full queue), it waits for the other thread to take out the element before continuing.

the difference between. Wait (), sleep ()
    • Wait (): an instance method that is defined in the object class. Calling the wait method on the specified object causes the current thread to enter a wait state (provided that the current thread holds the object's monitor), and the current thread frees the monitor for the object, so that other threads have access to the object's monitor. When another thread acquires the monitor of the object and takes the desired action, it can call the Notify method to wake up the thread before it enters the wait state.

    • Sleep (): A static method in the thread class that allows the current thread to hibernate so that other threads have an opportunity to execute. A thread that enters hibernation does not release the locks it holds.

29. Usage and advantages of thread pool
    • Advantage : The reuse of threads avoids the overhead of repeatedly creating and destroying threads; using thread pooling for unified management of threads can reduce the number of concurrent threads, and too many threads tend to waste too much time on thread context switching and threading synchronization.

    • Usage : We can call a constructor of Threadpoolexecutor to create a thread pool ourselves. But normally we can use the static factory method provided by the executors class to make it easier to create a thread pool object. Once the thread pool object has been created, we can invoke the Submit method to commit the task to the thread pool to execute it, and then we'll remember to call the shutdown method to close it.

Detailed introduction to thread pool and analysis of implementation principles poke a deep understanding of the Java thread pool

comparison of efficiency between for-each and conventional for loop

on this question we look directly at "effective Java" to give us the answer:

For-each can make the code clearer and reduce the chance of error. The following idiomatic code applies to collections and array types:

for (Element e : elements) {    doSomething(e);
}

There is no performance penalty when using the For-each loop compared to a regular for loop, even if the array is iterated. In fact, in some cases it can also bring a slight performance boost because it calculates the upper limit of the array index only once.

31. Brief description of the differences between Java IO and NiO
    • Java IO is stream-oriented, which means that we need to read one or more bytes from the stream until all the bytes are read, and NIO is buffer-oriented, that is, it reads the data into a buffer and then handles the data in the buffer accordingly.

    • Java io is blocking io, and NIO is non-blocking IO.

    • There is a thing called a selector (selector) in Java NiO that allows you to register multiple channels (channel) on a selector and then use a thread to monitor these channels: if there is one in these channels ready to start reading or writing, The corresponding channel is started to read and write. While waiting for a channel to become readable/writable, the thread that is requesting read and write operations on the channel can do something else.

Further instructions please poke Java nio with IO

32. The function and principle of reflection

The effect of reflection is, in a nutshell, the various definitions of the class at run time, such as what properties and methods are defined. The principle is to obtain various kinds of information about the class object.

For more information, see the reflection of the Java Core Technology point

the generic mechanism in Java

For a detailed description of the generic mechanism, directly poke the generics of the Java Core Technology point

new features of Java 7 and Java 8

Here are two summaries of the very good: new features of Java 7 new features of Java 8

35. Common Design Patterns

The so-called "design pattern" is but a few common software design methods in object-oriented programming, and after the practical test, these design methods can solve some requirements in their own scenario, so they become the "design pattern" which is now widely circulated. In other words, formal design patterns are spawned by the fact that there are some tricky problems in some scenarios. With this in mind, we should fully understand the background of the design pattern and what the main contradiction it solves.

Commonly used design patterns can be divided into the following three major categories:

    • Create mode: Includes the Factory mode (can be further divided into simple Factory mode, factory method mode, abstract Factory mode), builder mode, singleton mode.

    • Structural mode: Including adapter mode, bridge mode, decoration mode, appearance mode, enjoy meta mode, proxy mode.

    • Behavioral patterns: Including command mode, mediator mode, observer mode, State mode, and policy mode.

For a detailed description of each mode, refer to the diagram design pattern

basic usage of the JNI

about JNI, here's a good article: Jni in Android

37. Definition, application scenario and principle of dynamic agent

for dynamic proxies, see the dynamic agent at the Java Core Technology point directly

38. Basic concepts and use of annotations
    • Annotations can be thought of as "enhanced annotations," which can explain things to the compiler, to the virtual machine.

    • Annotations are code that describes Java code that can be parsed by the compiler, and annotation processing tools can parse annotations at run time. The annotation itself is "passive" information, only the active resolution of it makes sense.

    • In addition to passing information to the compiler/virtual machine, we can also use annotations to generate some "templated" code.

For further analysis of annotations, please refer to the notes of the Java Core Technology point

Is that enough for you? Of course not. The above listed in the interview about Java's common problems, but also mostly Java technology system core technology points, through these problems caused by a series of problems is for us to point out the perfect knowledge of our own system of a road, we have to do is to follow this path persist:)

Java Interview--4

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.