Summary of basic knowledge points in Java Learning---interview

Source: Internet
Author: User
Tags finally block instance method int size static class thread class volatile

the difference between sleep and wait in Java
① These two methods come from different classes, namely, sleep comes from the thread class, and wait comes from the object class. Sleep is the static class method of thread, who calls who goes to sleep, even if you call B's Sleep method in a thread, actually a goes to sleep, to let the B thread sleep to call sleep in B's code. ② Lock: The most important thing is that the sleep method does not release the lock, and the wait method frees the lock so that other threads can use the synchronization control block or method. Sleep does not sell system resources; Wait is the thread waiting for the pool to wait, to assign system resources, and other threads to consume the CPU. The general wait does not add a time limit, because if the wait thread runs out of resources, it is useless to wait for all threads in the Notify/notifyall wake-up waiting pool to be called by other threads before it enters the ready queue to wait for the OS to allocate system resources. Sleep (milliseconds) can be specified by time to wake it up automatically, if the time is less than the interrupt () force interrupt. The role of Thread.Sleep (0) is "triggering the operating system to immediately re-compete with the CPU". ③ Use range: Wait,notify and notifyall can only be used in synchronous control methods or synchronization control blocks, and sleep can be used anywhere.   synchronized (x) {       x.notify ()      //or Wait ()    }
The difference between HashMap and Hashtable in Java
① Historical reasons: Hashtable is to give the old Dictonary class,  HashMap is Java1.2 introduced a map interface of an implementation ②hashmap allow null key value pairs, and Hashtable does not allow ③hashtable synchronization, And HashMap is more efficient than Hashtable.
Please outline the difference between throw and throws in an anomaly.
①throw represents an action that throws an abnormal action; throws represents a state, which means that a method may have an exception thrown ②throw used in a method implementation, and throws used in a method declaration ③throw can only be used to throw an exception, while throws may throw multiple exceptions
the difference between forward and redirect
Forward:    Credirect, B, A   
a summary of memory overflow
Memory overflow out of memory, refers to the program in the application of the RAM, there is not enough memory space for its use, there is an out-of-memory; for example, an integer is applied, but a long can be stored to save it. Memory leak memories leak, refers to the program after the application of memory, can not release the requested memory space, a memory leak damage may be ignored, but the memory leak accumulation of serious consequences, no matter how much memory, sooner or later will be occupied. Memory leak will eventually result in out of memory! A memory leak is when you request a system to allocate memory for use (new), but you don't return it after you've used it (delete), and you can't access the memory you're applying to (maybe you lost the address), and the system can't assign it to the required program again.
A summary of enumerations

enumerated types of things: https://www.cnblogs.com/hyl8218/p/5088287.html

The enumeration type conforms to the generic pattern Class enum<e extends Enum<e>>, and E represents the name of the enumeration type. Each value of the enumeration type is mapped to the protected enum (string name, int ordinal) constructor, where each value's name is converted to a string, and the ordinal setting indicates the order in which this setting was created.

http return Code Analysis

301:-permanent movement. The requested resource has been permanently moved to the new URI, the return information will include the new URI, and the browser will automatically redirect to the new URI. Any future new requests should be replaced with a new URI
302:-temporary movement. Similar to 301. But resources are only temporarily moved. The client should continue to use the original URI

304:-If the client sends a conditional GET request and the request is allowed, and the contents of the document (since the last time it was accessed or according to the requested condition) have not changed, the server should return this 304 status code:
403:-represents a client-side error, which refers to the ability of the server to process the request, but denies access to the authorization.
The 404:-server was unable to find resources (Web pages) based on client requests. With this code, the Web designer can set up a personalized page that "the resource you requested could not be found"
500:-Server Internal Error, unable to complete request

What are the original data types in Java, and what are their sizes and corresponding encapsulation classes?
    • Byte--1 Byte--byte
    • Short--2 Bytes--short
    • Int--4 Bytes--integer
    • Long--8 Bytes--long
    • Float--4 bytes--float
    • Double--8 bytes--double
    • Char--2 Bytes--character
    • Boolean —————— Boolean

The Boolean data type is False if it is not true.

This data type represents 1 bit, 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.

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.

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.
What are the methods defined in object?
    • Clone ()
    • Equals ()
    • Hashcode ()
    • ToString ()
    • Notify ()
    • Notifyall ()
    • Wait ()
    • Finalize ()
    • GetClass ()
What is the role of hashcode?

Please refer to the basic principle and implementation of hash table

ArrayList, LinkedList, what is the difference between 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
What is the difference between String, StringBuilder, 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
The features and usage of MAP, Set, List, Queue, stack.
    • Map<k, the data type that stores the key-value pairs in the v= "" >: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. </k,>
    • Set<e>: A duplicate element is 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>:java the queue interface in the collection frame, which represents the "FIFO" queue. Support for operations such as add (E Element), remove ().
    • The Stack<e>: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.

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
The realization 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 map source HashMap source Analysis

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, 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 be seen as a hashmap that remembers the order in which elements are inserted.
What is the difference between collection and collections?
    • Collection<e> is the basic interface in the Java collection framework;
    • 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 "try-catch-finally", if the Try statement block contains a "return" statement, will the finally statement block execute?

will 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".

Exception hierarchies 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 object-oriented

Three major characteristics: encapsulation, inheritance, polymorphism.

Override, the meaning and difference of overload
    • 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
The difference between an interface and an abstract class
    • Interface is a convention that implements the class of an interface to 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).

The difference between a static inner class and a 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.

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

Describe two ways to create 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.
A brief introduction to the thread synchronization method 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.
Describe what kinds of granularity locks are in Java

In Java, you can lock classes, objects, methods, or blocks of code.

A solution to the problem of "producer-consumer"

To use a blocking queue:

public class Blockingqueuetest {private int size =; Private arrayblockingqueue<integer> blockingqueue = new Arra yblockingqueue<> (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 the blocking queue queue.take (); System.out.println ("queue remainder" + queue.size () + "elements"); } catch (Interruptedexception e) {}}}} class Producer extends thread{@Override public void Run () {while (true) {try {//Insert an element into a blocking queue queue.put (1); System.out.println ("Queue remaining space:" + (Size-queue.size ())); } catch (Interruptedexception e) {}}}}}

The design idea and function 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.

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.
Usage and advantage 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.
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.

Brief description of the difference 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.

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.

Generic mechanisms in Java

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

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.
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.

Summary of basic knowledge points in Java Learning---interview

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.