Java Interview Core Tutorial |java interview basic Knowledge points Summary

Source: Internet
Author: User
What are the original data types in Java, and what are their sizes and corresponding encapsulation classes? Byte--1 byte--byteshort--2 bytes--shortint--4 bytes--integerlong--8 bytes--longfloat--4 bytes--floatdouble--8 bytes- -doublechar--2 Bytes--characterboolean —————— The Booleanboolean 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. You can click to join the group: "Advanced Java Architecture": 854180697 There is a Java senior Daniel Live explanation of Knowledge point is the high-end route (if you want to change jobs but technology is not enough Or a bottleneck at work. I've got a free live course on Java, which is about the high-end Knowledge Point Foundation bad mistake into yo as long as you have 1-5 years of development experience can add group to find me to the classroom link Note: Is free of development experience mistakenly into OH) talk about "= =" and "Equals ()" difference. Think in Java says: "Relational operators generate a Boolean result that calculates the relationship between the operands ' values." "= =" Determines whether the memory address of the two objects is the same, applies to the original data type and enum type(Their variables store the value itself, whereas a reference type variable stores a reference); equals is a method of the object class, and object implements it as a comparison of memory addresses, and 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: Typically, the reference returned when we create an object with the new operator is a strongly-referenced soft reference: If an object can only be reached by a soft reference, the object will be reclaimed when it is not in memory, can be used in the picture cache, and the system will automatically reclaim the bitmap weak reference that is no longer in use when it is low: 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 picture cache, this time as long as the bitmap no longer used will be recycled virtual reference: Virtual reference is the most "weak" reference in Java, through it even unable to 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? What is the role of Clone () equals () Hashcode () toString () notify () Notifyall () Wait () Finalize () GetClass () hashcode? Please refer to the basic principle and implementation of the 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: The internal use of linked lists to store elements, support for fast insertion/deletion of elements, but does not support the efficient random access to the vector: Can be seen as a thread-safe version of Arrayliststring, StringBuilder, what is the difference between stringbuffer? String: Immutable character sequence, to add new characters to it, you need to create a new string object StringBuilder: A variable character sequence that supports adding new characters to it (without creating a new object) StringBuffer: It can be considered as a thread-safe version of Stringbuildermap, Set, List, Queue, stack features and usage. The data type that stores the key-value pairs in the Map: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 is used to obtain the value corresponding to the key and to insert a key-value pair into the mapping table. Set: 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. The list type in the collection framework in List:java implements this interface, which represents an ordered sequence. Support for operations such as get (int index), add (e e). Queue:java the queue interface in the collection frame, which represents the "FIFO" queue. Support for operations such as add (E Element), remove (). The Stack: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 allowed to have null keys and null values in HashMap, while Hashtable does not allow HashMap to be implemented in a simple sense. The bottom-level implementation of HASHMAP is "a hash table based on the Zipper method". Detailed analysis please refer to the Map source code analysis of the HashMap source code to analyze the implementation principle of Concurrenthashmap Concurrenthashmap is to support concurrent read and write HashMap, it is characterized by the reading of data without locking, When writing data, you can ensure that the lock granularity is 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: concurrenthashmaptreemap of concurrent containers, Linkedhashmap, what is the difference between hashmap? The underlying implementation of HASHMAP is a hash table, so the elements stored inside it are unordered, and the underlying implementation of the TREEMAP is the 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 is the basic interface in the Java Collection Framework; collections is J.The AVA Collection Framework provides a tool class 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: the System.exit () method is called and the JVM "crashes". 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). Java object-oriented three features and meanings of three major features: encapsulation, inheritance, polymorphism. Override, meaning and difference of overload override means "override", which is a redefinition of the same method in the parent class by the subclass overload represents "overloaded", That is, defining a new method interface with the same name as the defined method, but with a different signature than the interface is a convention, the class that implements the interface follows this convention; Abstract classes are inherently a class, and the cost of using abstract classes is larger than interfaces. The interface is compared to the abstract class 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 A static inner class does not hold a reference to a perimeter class, whereas a non-static inner class implicitly holds a reference to the perimeter class. The implementation principle of polymorphic in Java so-called polymorphism, refers to the parent class reference to the child class object, call the method will call the implementation of the subclass rather than the implementation of the parent class。 The key to polymorphic implementations is "dynamic binding." Detailed introduction The internal implementation mechanism of the dynamic binding of Java the two methods of creating a new thread in Java inherit the thread class (assuming the subclass is Mythread), rewrite the Run () method, and then new a Mythread object and call Start () to start the new thread. 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 description of thread synchronization in Java Volatile:java Memory model guarantees The write happens of the same volatile variable before read it; synchronized: You can lock a block of code or a method, The "locked" place is called the critical section, and the thread that enters the critical section acquires the object's monitor, so that other threads that attempt to enter the critical section are blocked because they cannot get the monitor. 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. In Java, you can lock down classes, objects, methods, or blocks of code with a description of what kind of granularity is in Java. A solution to the problem of "producer-consumer" use a blocking queue: public class Blockingqueuetest {private int size = $; Private Arrayblockingqueue Blockingque UE = 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 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) {}}}}}threadlocal the design concept and role of threadlocal is to provide local variables within the thread, When accessed in a multithreaded environment, the threadlocal variables within each thread are guaranteed to be independent of each other. 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 is Arrayblockingqueue, and the Countdownlatch class acts 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. Wait (), the difference between 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 releases the monit of the corresponding object.Or, so that other threads have a chance to get the monitor of the object. 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. Thread pool usage and advantages: 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 the efficiency of For-each with conventional for loop for this question we look directly at the effective Java solution: 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. A 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 every time until all the bytes are read; 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 action of reflection and the function of the principle reflex are, in a nutshell, the various defining information for the runtime to obtain the class, such as what properties and methods are defined. The principle is to get its various objects through the class objectInformation. Generic mechanism in Java for a detailed introduction to the generic mechanism, directly poke the generic design pattern of the Java Core Technology point, the so-called "design pattern", but some common software design methods in object-oriented programming, and through the practice of testing, these design techniques in their respective scenarios can solve some requirements, As a result, they are now widely circulated as "design patterns". 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. Common design patterns can be divided into the following three categories: the creation mode: including 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. The basic concept of annotations and the use of 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. 91 reads  

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.