Home >Java >JavaInterview questions >Sharing of common Java key interview questions
1. What is a Java virtual machine? Why is Java called a "platform-independent programming language"?
(Recommendations for more related interview questions: java interview questions and answers)
The java virtual machine is a virtual machine process that executes bytecode files (.class). . The java source program (.java) is compiled into a bytecode file (.class) by the compiler. Then the bytecode file will be interpreted into machine code by the Java virtual machine (the machine code of different platforms is different). Use machine code to operate hardware and operating systems. Because different platforms are equipped with different JVMs, they can interpret the same .class file into the machine code required by different platforms. It is precisely because of the existence of JVM that Java is called a platform-independent programming language.
2. What is the difference between JDK and JRE?
Java Development Kit (JDK) is a complete Java software development package, including JRE, compiler and other tools (such as: JavaDoc, Java debugger), which allows developers to develop, compile and execute Java application. Java Runtime Environment (JRE). It includes Java virtual machine, Java core class library and support files. It does not include development tools (JDK), compilers, debuggers, and other tools.
3. What does the "static" keyword mean? Is it possible to override a private or static method in Java?
The "static" keyword indicates that a member variable or member method can be accessed without an instance variable of the class to which it belongs.
Static methods in Java cannot be overridden because method overrides are based on dynamic binding at runtime, while static methods are statically bound at compile time. Static methods are not related to any instance of the class, so conceptually they do not apply. Private methods cannot be overridden in Java, because private variables and methods can only be used in the current class. If other classes inherit the current class, they cannot access private variables or methods, and of course they cannot be overridden.
4. Can non-static variables be accessed in a static environment?
Static variables belong to classes in Java, and their values are the same in all instances. When a class is loaded by the Java virtual machine, static variables are initialized. If your code attempts to access non-static variables without using an instance, the compiler will report an error because these variables have not yet been created and are not associated with any instance.
5.What are the data types supported by Java? What is an automatic unpacking box?
The data types supported by Java include two types: one is the basic data type, including byte, char, short, boolean, int, long, float, double; the other is the reference type: such as String, etc. In fact, it is a reference to an object. What is stored in the virtual stack in the JVM is the address of the object. The created object is actually in the heap. The process of finding the object in the heap through the address is a reference type. Autoboxing is the conversion of the Java compiler between basic data types and corresponding object packaging types, that is, int is converted into Integer. Automatic unboxing is the process of converting Integer into int by calling its method.
6.What do method overriding and method overloading in Java mean?
Method overloading in Java occurs when two or more methods in the same class have the same method name but different parameters. Overriding is a manifestation of polymorphism in a class. Method overriding means that the subclass redefines the method of the parent class. Method overrides must have the same method name, parameter list and return type. An overrider may not restrict access to the methods it overrides. In Java, subclasses can inherit the methods of the parent class, and there is no need to rewrite the same methods. But sometimes the subclass does not want to inherit the methods of the parent class unchanged, but wants to make certain modifications, so method rewriting is used. Method overriding is also called method overwriting.
7.What is a constructor method in Java? What is constructor overloading? What is copy constructor?
When a new object is created, the constructor will be called. Every class has constructor methods. In the case where the programmer does not provide a constructor for the class, the Java compiler will create a default constructor for the class. Constructor overloading and method overloading in Java are very similar. You can create multiple constructors for a class. Each constructor must have its own unique parameter list. Java does not support copy constructors. If you do not write the constructor yourself, Java will not create a default copy constructor.
8. Does Java support multiple inheritance?
Classes in Java do not support multiple inheritance, but only single inheritance (that is, a class has only one parent class). However, interfaces in Java support multiple inheritance, that is, a sub-interface can have multiple parent interfaces. (The function of an interface is to extend the functions of an object. A sub-interface inherits multiple parent interfaces, indicating that the sub-interface extends multiple functions. When a class implements the interface, the class extends the corresponding functions).
9. What is the difference between interface and abstract class?
From the design level, abstraction is the abstraction of classes and a template design. Interfaces are the abstraction of behavior and a specification of behavior.
Java provides and supports the creation of abstract classes and interfaces. Their implementations have something in common, but the differences are:
All methods in the interface are implicitly abstract. An abstract class can contain both abstract and non-abstract methods; a class can implement many interfaces, but can only inherit one abstract class; a class does not need to implement all the methods declared by abstract classes and interfaces. Of course, in this case, Classes must also be declared abstract; abstract classes can implement interfaces without providing interface method implementations; variables declared in Java interfaces are final by default. Abstract classes can contain non-final variables; member functions in Java interfaces are public by default. Member functions of abstract classes can be private, protected or public; interfaces are absolutely abstract and cannot be instantiated. An abstract class cannot be instantiated, but it can be called if it contains a main method.
You can also refer to the difference between abstract classes and interfaces in JDK8.
10. What are pass-by-value and pass-by-reference?
It is generally believed that the transfer in Java is by value. The transfer of instance objects in Java is by reference.
Value transfer is for basic variables, and a copy of the variable is transferred. Changing the copy does not affect the original variable; reference transfer is generally for object variables, and the object is transferred. A copy of the address, not the original object itself.
11. What is the difference between process and thread?
A process is an executing application, a dynamic form of the program, and the basic unit that occupies resources such as CPU and memory. Moreover, processes are independent of each other and communication is difficult. During the execution of a process, Contains relatively fixed entrances, execution sequences, and exits; a thread is an execution sequence within a process and belongs to a certain process. A process can have multiple threads. Threads cannot occupy resources such as CPU and memory, and threads share a piece of memory. Area, communication is more convenient, and the thread entry execution sequence and these processes are controlled by the application program.
12. How many different ways are there to create a thread? Which one do you prefer? Why?
There are four ways to create threads.
Inherit the Thread class; implement the Runnable interface; the application can use the Executor framework to create a thread pool; implement the Callable interface.
Implementing the Runnable interface is more popular because it does not require inheriting the Thread class. In the case where other objects have been inherited in the application design, this requires multiple inheritance (and Java does not support multiple inheritance), and only interfaces can be implemented. At the same time, the thread pool is also very efficient and easy to implement and use.
13. Briefly explain the several available states of threads.
New (new): A new thread object is created. Runnable: After the thread object is created, other threads (such as the main thread) call the start () method of the object. The thread in this state is located in the runnable thread pool, waiting to be selected by thread scheduling to obtain the right to use the CPU. Running: The thread in the runnable state obtains the CPU time slice (timeslice) and executes the program code. Blocking (block): The blocking state means that the thread gives up the right to use the CPU for some reason, that is, it gives up the CPU timeslice and temporarily stops running. Until the thread enters the runnable state, it has the opportunity to obtain the cpu timeslice again and move to the running state. There are three types of blocking situations:
(1). Waiting for blocking: The running thread executes the o.wait () method, and the JVM will put the thread into the waiting queue (waiting queue).
(2). Synchronous blocking: When a running thread acquires the synchronization lock of an object, if the synchronization lock is occupied by another thread, the JVM will put the thread into the lock pool. )middle.
(3). Other blocking: When a running thread executes the Thread.sleep (long ms) or t.join () method, or an I/O request is issued, the JVM will set the thread to is in blocking state. When the sleep () state times out, join () waits for the thread to terminate or times out, or the I/O processing is completed, the thread returns to the runnable state.
Death (dead): When the execution of the thread's run() and main() methods ends, or the run() method exits due to an exception, the thread ends its life cycle. Dead threads cannot be resurrected.
#14. What is the difference between synchronized methods and synchronized code blocks?
Why use synchronization?
Java allows multi-threaded concurrency control. When multiple threads operate a shareable resource variable at the same time (add, delete, modify, check), it will lead to inaccurate data and conflicts with each other. Therefore, synchronization locks are added to avoid This thread is called by other threads before completing the operation, thus ensuring the uniqueness and accuracy of the variable.
Difference
The synchronization method uses this or the current class object as the lock by default; the synchronization code block can choose what to lock, which is more fine-grained than the synchronization method. We can choose only Synchronization will cause synchronization problems in part of the code rather than the entire method; the synchronization method uses the keyword synchronized to modify the method, and the synchronization code block mainly modifies the code that needs to be synchronized, and uses synchronized (object) {code content} to modify it;
15. How is thread synchronization done inside the monitor? What level of synchronization should the program do?
Monitors and locks are used together in the Java virtual machine. The monitor monitors a synchronized code block to ensure that only one thread executes the synchronized code block at a time. Each monitor is associated with an object reference. The thread is not allowed to execute synchronized code before acquiring the lock.
16. What is deadlock?
The so-called deadlock refers to a deadlock (waiting for each other) caused by multiple processes competing for resources. Without external force, these processes will be unable to move forward. Four necessary conditions for deadlock:
Mutual exclusion conditions: The process requires exclusive control of the allocated resources (such as printers), that is, a certain resource is only occupied by one process within a period of time. At this time, if other processes request the resource, the requesting process can only wait. Non-deprivation condition: The resources obtained by a process cannot be forcibly taken away by other processes before they are completely used, that is, they can only be released by the process that obtained the resources (it can only be released actively). Request and hold conditions: The process has held at least one resource, but has made a new resource request, and the resource has been occupied by another process. At this time, the requesting process is blocked, but it will keep the resources it has obtained. Circular waiting condition: There is a ==cyclic waiting chain== for process resources. The resources obtained by each process in the chain are simultaneously requested by the next process in the chain.
17. How to ensure that N threads can access N resources without causing deadlock?
When using multi-threading, a very simple way to avoid deadlock is: ==Specify the order in which locks are acquired==, and force threads to acquire locks in the specified order. Therefore, if all threads lock and release locks in the same order, there will be no deadlock.
18.What are the basic interfaces of Java collection class framework?
The collection class interface specifies a set of objects called elements. Each concrete implementation class of the collection class interface can choose to save and sort the elements in its own way. Some collection classes allow duplicate keys, while others do not.
Java collection classes provide a set of well-designed interfaces and classes that support operations on a set of objects. The most basic interfaces in Java collection classes are:
Collection: represents a group of objects, each object is its child element. Set: Collection that does not contain duplicate elements. List: A collection that is ordered and can contain repeated elements. Map: An object that can map keys to values. Keys cannot be repeated.
19. Why does the collection class not implement the Cloneable and Serializable interfaces?
The semantics and meaning of cloning or serialization are related to the specific implementation. Therefore, it is up to the specific implementation of the collection class to determine how it is cloned or serialized.
20.What is an iterator?
The Iterator interface provides many methods for iterating over collection elements. Every collection class contains
iteration methods that return iterator instances. The iterator can delete elements of the underlying collection during the iteration process, but it cannot be deleted directly by calling
remove(Object Obj) of the collection. It can be deleted through the remove() method of the iterator.
21.What is the difference between Iterator and ListIterator?
Their differences are listed below:
Iterator can be used to traverse Set and List collections, but ListIterator can only be used to traverse List. Iterator can only traverse a collection forward, while ListIterator can traverse both forward and backward. ListIterator implements the Iterator interface and includes other functions, such as adding elements, replacing elements, getting the index of the previous and next elements, etc.
22. What is the difference between fail-fast and fail-safe?
Iterator's safety failure is based on copying the underlying collection, so it is not affected by modifications on the source collection. All collection classes under the java.util package are fail-fast, and all classes under the java.util.concurrent package are fail-safe. A fail-fast iterator will throw a ConcurrentModificationException exception, while a fail-safe iterator will never throw such an exception.
33. How does HashMap work in Java?
HashMap in Java stores elements in the form of key-value pairs. HashMap requires a hash function, which uses hashCode() and equals() methods to add and retrieve elements to/from the collection. When the put() method is called, the HashMap will calculate the hash value of the key and then store the key-value pair at the appropriate index in the collection. If the key already exists, the value will be updated to the new value. Some important characteristics of HashMap are its capacity, load factor and threshold resizing.
34. What is the importance of hashCode() and equals() methods?
HashMap in Java uses the hashCode() and equals() methods to determine the index of the key-value pair. These two methods are also used when getting the value based on the key. If these two methods are not implemented correctly, two different keys may have the same hash value and, therefore, may be considered equal by the collection. Moreover, these two methods are also used to find duplicate elements. Therefore, the implementation of these two methods is crucial to the accuracy and correctness of HashMap.
35.What is the difference between HashMap and Hashtable?
HashMap and Hashtable both implement the Map interface, so many features are very similar. However, they have the following differences:
HashMap allows keys and values to be null, while Hashtable does not allow keys or values to be null. Hashtable is synchronous, HashMap is not. Therefore, HashMap is more suitable for single-threaded environments, while Hashtable is suitable for multi-threaded environments. HashMap provides a collection of keys that an application can iterate over, therefore, HashMap is fail-fast. On the other hand, Hashtable provides an enumeration of keys. It is generally believed that Hashtable is a legacy class.
36. What is the difference between array (Array) and list (ArrayList)? When should you use Array instead of ArrayList?
Array can contain basic types and object types, and ArrayList can only contain object types. The size of Array is fixed, and the size of ArrayList changes dynamically. ArrayList provides more methods and features, such as: addAll(), removeAll(), iterator(), etc. For basic types of data, collections use autoboxing to reduce coding effort. However, this approach is relatively slow when dealing with fixed-size primitive data types.
37. What is the difference between ArrayList and LinkedList?
Both ArrayList and LinkedList implement the List interface. They have the following differences:
ArrayList is an index-based data interface, and its bottom layer is an array. It can perform random access to elements with O(1) time complexity. Correspondingly, LinkedList stores its data in the form of == element list ==. Each element is linked to its previous and next elements. In this case, the time to find an element is complicated. The degree is O(n).
Compared to ArrayList, LinkedList's insertion, addition, and deletion operations are faster because when an element is added to any position in the collection, there is no need to recalculate the size or update the index like an array. LinkedList takes up more memory than ArrayList because LinkedList stores two references for each node, one pointing to the previous element and one pointing to the next element.
38.What do the Comparable and Comparator interfaces do? List their differences.
Java provides a Comparable interface that contains only one compareTo() method. This method can sort two objects. Specifically, it returns negative numbers, 0, and positive numbers to indicate that the existing object is less than, equal to, or greater than the input object.
Java provides the Comparator interface containing two methods: compare() and equals(). The compare() method is used to sort two input parameters and returns a negative number, 0. A positive number indicates that the first parameter is less than, equal to, or greater than the second parameter. The equals() method requires an object as a parameter, which is used to determine whether the input parameter is equal to the comparator. This method returns true only if the input parameter is also a comparator and the sorting result of the input parameter and the current comparator is the same.
Comparable & Comparator are both used to achieve comparison and sorting of elements in a collection. However, Comparable is a sorting implemented by a method defined inside the collection, and Comparator is a sorting implemented outside the collection. Therefore, if you want to implement For sorting, you need to define methods of the Comparator interface outside the collection or implement methods of the Comparable interface within the collection. Comparator is located under the package java.util, and Comparable is located under the package java.lang. Comparable is an interface that needs to be implemented by an object itself that already supports self-comparison (such as String and Integer. It can complete the comparison operation by itself and has implemented the Comparable interface) If a custom class can be sorted after being added to the list container, it can implement the Comparable interface. When sorting using the sort method of the Collections class, if you do not specify a Comparator, then it will be sorted in natural order. The natural order here is to implement the Comparable interface setting. certain sorting method.
The Comparator is a dedicated comparator. When the object does not support self-comparison or the self-comparison function cannot meet your requirements, you can write a comparator to complete the size comparison between the two objects. It can be said that the difference between one is that the comparison is completed by oneself, and the other is that the external program implements the comparison. Using Comparator is a strategy design pattern, which means not changing the object itself, but using a strategy object to change its behavior. For example: If you want to sort integers by absolute size, Integer does not meet the requirements. You do not need to modify the Integer class (in fact, you cannot do this) to change its sorting behavior. You only need to use a Comparator interface that implements the Comparator interface. Just use the object to control its sorting.
39.What is Java Priority Queue (Priority Queue)?
PriorityQueue is an unbounded queue based on a priority heap, and its elements are sorted in natural order. When creating it, we can provide it with a comparator responsible for sorting the elements. PriorityQueue does not allow null values because they have no natural order, or they do not have any associated comparator. Finally, PriorityQueue is not thread-safe, and the time complexity of enqueuing and dequeuing is O(log(n)).
40. Do you understand big-O notation? Can you give examples of different data structures?
Big O notation describes the size of the algorithm or an asymptotic upper bound when the elements in the data structure increase.
Big O notation can also be used to describe other behaviors, such as: memory consumption. Because collection classes are actually data structures, we generally use Big O notation to choose the best implementation based on time, memory, and performance. Big O notation can give a good idea of performance on large amounts of data.
41.What are the differences between the Enumeration interface and the Iterator interface?
Enumeration is 2 times faster than Iterator and takes up less memory. However, Iterator is far safer than Enumeration because other threads cannot modify the objects in the collection being traversed by iterator. At the same time, Iterator allows the caller to delete elements in the underlying collection, which is not possible with Enumeration.
42.What is the difference between HashSet and TreeSet?
HashSet is implemented by a hash table, therefore, its elements are unordered. The time complexity of add(), remove(), and contains() methods is O(1). On the other hand, TreeSet is implemented by a tree structure, and the elements in it are ordered. Therefore, the time complexity of the add(), remove(), and contains() methods is O(logn).
43.What is the purpose of garbage collection in Java? When does garbage collection occur?
Garbage collection is performed when there are unreferenced objects or objects that exceed the scope in the memory.
The purpose of garbage collection is to identify and discard objects that are no longer used by the application to release and reuse resources.
44.What will System.gc() and Runtime.gc() do?
These two methods are used to prompt the JVM to perform garbage collection. However, whether garbage collection starts immediately or is delayed depends on the JVM.
45.When is the finalize() method called? What is the purpose of destructor (finalization)?
When the garbage collector decides to recycle an object, it will run the finalize() method of the object. But unfortunately in Java, if the memory is always sufficient, then garbage collection may never happen. progress, that is to say, filalize() may never be executed. Obviously, it is unreliable to expect it to do the finishing work. So what exactly does finalize() do? Its main purpose is to reclaim memory allocated by special channels. Java programs have garbage collectors, so under normal circumstances, programmers do not need to worry about memory issues. But there is a JNI (Java Native Interface) that calls a non-Java program (C or C), and the job of finalize() is to reclaim this part of the memory.
Calling timing: When the garbage collector wants to declare an object dead, it must go through at least two marking processes: if the object finds that there is no reference chain connected to GC Roots after performing reachability analysis, it will is marked for the first time, and determines whether to execute the finalizer() method. If the object overrides the finalizer() method and has not been called by the virtual machine, then the object will be placed in the F-Queue queue and will be later used by a virtual machine. The execution of the low-priority Finalizer thread area automatically created by the machine triggers the finalizer() method, but does not promise to wait for the end of its operation.
(Recommended tutorial: java course)
The purpose of finalization: the object’s last chance to escape death. (Just re-associate with any object on the reference chain.) However, it is not recommended. It is expensive to run, highly uncertain, and the calling order of each object cannot be guaranteed. Use try-finally or other alternatives.
46. If the reference to an object is set to null, will the garbage collector immediately release the memory occupied by the object?
No, this object will be recyclable in the next garbage collection cycle.
The memory occupied by the object will not be released immediately. If the reference of the object is set to null, it only disconnects the reference to the object in the current thread stack frame, and the garbage collector is a thread running in the background. It can only be used when the user thread runs to a safe point (safe point) or safe The object reference relationship will be scanned only in the area. If the object is not referenced, the object will be marked. At this time, the object memory will not be released immediately because some objects are recoverable (references are restored in the finalize method). Only when it is determined that the reference to the object cannot be restored will the object memory be cleared.
47.What is the structure of the Java heap? What is the Perm Gen space in the heap?
The JVM's heap is the runtime data area, and all class instances and arrays allocate memory on the heap. It is created when the JVM starts. The heap memory occupied by the object is reclaimed by the automatic memory management system, that is, the garbage collector.
Heap memory is composed of living and dead objects. Surviving objects are accessible to the application and will not be garbage collected. Dead objects are objects that are inaccessible to the application and have not yet been reclaimed by the garbage collector. Until the garbage collector collects these objects, they will continue to occupy heap memory space.
The permanent generation is used to store static files, such as Java classes, methods, etc. The persistent generation has no significant impact on garbage collection, but some applications may dynamically generate or call some classes, such as Hibernate, etc. In this case, a relatively large persistent generation space needs to be set up to store these newly added classes during operation, permanently. The code generally contains:
Methods of the class (bytecode...)
Class name (Sring object)
Constant information read from the .class file
Object list and type list related to the class object ( e.g., array of method objects).
Internal objects created by JVM
Information for JIT compiler optimization
48. Serial collector and throughput collector What's the difference?
The throughput collector uses a parallel version of the young generation garbage collector, which is used for applications with medium-sized and large-scale data. The serial collector is sufficient for most small applications (which require about 100M of memory on modern processors).
49. In Java, when can objects be garbage collected?
When an object is unreachable to GC Roots, try to recycle the object in the next garbage collection cycle. If the object overrides the finalize() method and successfully saves itself in this method (assigning itself to something) reference), then the object will not be recycled. But if the object does not override the finalize() method or has already executed this method and fails to save itself, the object will be recycled.
50.Will garbage collection occur in the permanent generation of JVM?
Garbage collection will not occur in the permanent generation. If the permanent generation is full or exceeds the critical value, a full garbage collection (Full GC) will be triggered. If you look carefully at the output of the garbage collector, you will see that the permanent generation is also collected. This is why correct permanent generation size is very important to avoid Full GC. Please refer to Java8: From Permanent Generation to Metadata Area
(Note: The permanent generation has been removed in Java8, and a new native memory area called metadata area has been added)
51.Java What are the two exception types of ? What's the difference between them?
There are two kinds of exceptions in Java: checked exceptions and unchecked exceptions. Unchecked exceptions do not need to be declared on a method or constructor, even though execution of the method or constructor may throw such an exception, and unchecked exceptions can propagate outside the method or constructor. Instead, checked exceptions must be declared on the method or constructor using the throws statement. Here are some tips for Java exception handling.
Throwable includes errors (Error) and exceptions (Excetion)
Exception also includes runtime exceptions (RuntimeException, also called unchecked exceptions) and non-runtime exceptions (also called checked exceptions)
(1) Error means that the program cannot handle it. If OutOfMemoryError, etc., when these exceptions occur, the Java virtual machine will generally terminate the thread.
(2) Runtime exceptions are RuntimeException class and its subclasses, such as NullPointerException , IndexOutOfBoundsException, etc. These exceptions are unchecked exceptions that may occur when the program is running, so the program may or may not catch them. These errors are generally caused by logical errors in the program, and the program should start from a logical perspective. Try to avoid it as much as possible.
(3) Checked exceptions are exceptions other than runtime exceptions, and are also Exception and its subclasses. From a program perspective, these exceptions must be caught and checked, otherwise they cannot pass compilation. Such as IOException , SQLException, etc.
52.What is the difference between Exception and Error in Java?
Exception and Error are both subclasses of Throwable. Exception is used for exceptions that can be caught by user programs. Error defines exceptions that are not expected to be caught by user programs.
53.What is the difference between throw and throws?
Thethrow keyword is used to explicitly throw exceptions in the program. On the contrary, the throws statement is used to indicate exceptions that the method cannot handle. Each method must specify which exceptions cannot be handled, so the caller of the method can ensure that possible exceptions are handled. Multiple exceptions are separated by commas.
1. Throw is used inside the method, and Throws is used in the method declaration;
2. Throw is followed by the exception object, and Throws is followed by the exception type;
3. Throw can only be followed by one exception object. Multiple exception types can be declared at once after Throws.
54. After exception handling is completed, what will happen to the Exception object? ,
Exception objects will be recycled during the next garbage collection process.
55. What is the difference between finally code block and finalize() method?
The finally code block will be executed regardless of whether an exception is thrown. It is mainly used to release the resources occupied by the application. The finalize() method is a protected method of the Object class. It is called by the Java virtual machine before the object is garbage collected.
56. What is an Applet?
A java applet is a program that can be included in an HTML page and executed by a java-enabled client browser. Applets are mainly used to create dynamic interactive web applications.
57. Explain the life cycle of Applet.
Applet can go through the following states:
Init: It will be initialized every time it is loaded.
Start: Start executing the applet.
Stop: End the execution of the applet.
Destroy: Do the final cleanup before uninstalling the applet.
58. What happens when the applet is loaded?
First, create an instance of the applet control class, then initialize the applet, and finally start running.
59. What is the difference between Applet and ordinary Java application?
Applet runs in a Java-enabled browser. Java applications are independent Java programs that can run outside the browser. However, they all require a Java virtual machine.
Furthermore, a Java application requires a main function with a specific method signature to start execution. Java applets do not require such a function to start execution.
Finally, Java applets generally use very strict security policies, and Java applications generally use looser security policies.
60. What are the restrictions on Java applets?
Mainly due to security reasons, the following restrictions are imposed on applet:
applet cannot load class libraries or define local methods; cannot read and write files on the host; cannot read specific System properties; cannot initiate network connections except with the host; cannot start any other programs on the host.
61. What is an untrusted applet?
Untrusted applets are Java applets that cannot access or execute local system files. By default, all downloaded applets are untrusted.
62. What is the difference between an applet loaded from the network and an applet loaded from the local file system?
When an applet is loaded from the network, the applet is loaded by the applet class loader, which is restricted by the applet security manager.
When the applet is loaded from the client's local disk, the applet is loaded by the file system loader.
The applet loaded from the file system allows the client to read files, write files, load class libraries, and also allows the execution of other programs. However, it cannot pass bytecode verification.
63. What is an applet class loader? What will it do?
When an applet is loaded from the network, it is loaded by the applet class loader. Class loaders have their own java namespace hierarchy. The class loader will ensure that classes from the file system have a unique namespace, and classes from network resources have a unique namespace.
When the browser loads an applet over the network, the applet's class is placed in a private namespace associated with the applet's source. Then, those classes loaded by the class loader are verified by the validator. The validator checks whether the class file format complies with the Java language specification to ensure that stack overflow or underflow does not occur and that the parameters passed to the bytecode instructions are correct.
64. What is the applet security manager? What will it do?
The applet security manager is a mechanism for imposing restrictions on applets. A browser can have only one security manager. The security manager is created at startup and cannot be replaced or extended later.
65. What is the difference between pop-up selection menu (Choice) and list (List)?
Choice is displayed in a compact form, and you need to scroll down to see all the options. Only one option can be selected at a time in Choice. List can have multiple elements visible at the same time, and supports selecting one or more elements.
66. What is a layout manager?
Layout managers are used to organize components in containers.
67. What is the difference between a scroll bar (Scrollbar) and a scroll panel (JScrollPane)?
Scrollbar is a component, not a container. And ScrollPane is a container. ScrollPane handles scroll events itself.
68. Which Swing methods are thread-safe?
There are only 3 thread-safe methods: repaint(), revalidate(), and invalidate().
69. Name three components that support redrawing.
Canvas, Frame, Panel, and Applet support redrawing.
70. What is JDBC?
JDBC is an abstraction layer that allows users to choose between different databases. JDBC allows developers to write database applications in JAVA without having to worry about the details of the underlying specific database.
JDBC (Java DataBase Connectivity) is a set of object-oriented application programming interfaces (APIs). It formulates a unified standard interface for accessing various relational databases and provides standard implementations for various database manufacturers. Through JDBC technology, developers can write complete database applications using pure Java language and standard SQL statements, and truly realize the cross-platform nature of the software.
Usually use JDBC to complete the following operations:
1. Establish a connection with the database;
2. Send SQL statements to the database;
3. Process the results returned from the database;
JDBC has The following advantages:
1. JDBC is very similar to ODBC (Open Database Connectivity, that is, open database interconnection), which is easy for software developers to understand;
2. JDBC frees software developers from the complex driver writing work out, you can completely focus on business logic development;
3.JDBC supports a variety of relational databases, greatly increasing the portability of software;
4.JDBC API is object-oriented, and software developers can use commonly used The method is re-encapsulated to improve the reusability of the code;
71. What does database connection pool mean?
Interaction with the database, such as opening and closing database connections, may be time-consuming. Especially when the number of clients increases, it will consume a lot of resources and the cost is very high. Many database connections can be established and maintained in a pool when the application server starts. Connection requests are served from connections in the pool. After the connection is used up, the connection is returned to the pool to be used to satisfy more requests in the future.
72. What are the steps to make the RMI program run correctly?
In order for the RMI program to run correctly, the following steps must be included:
Compile all source files.
Use rmic to generate stub.
Start rmiregistry.
Start the RMI server.
Run the client program.
73. Explain Marshalling and demarshalling.
When an application wants to transfer a memory object across the network to another host or persist it to storage, it must convert the representation of the object in memory into an appropriate format. This process is called Marshalling, and the reverse is demarshalling.
74. Explain Serialization and Deserialization.
Java provides a mechanism called object serialization, which represents the object as a series of bytes, which contains the object's data, the object's type information, the type information of the data inside the object, and so on. Therefore, serialization can be seen as a way of flattening objects in order to store them on disk or read them from disk and reconstruct them. Deserialization is the reverse step of converting an object from a flat state into a live object.
75. What is Servlet?
Servlet is a Java class used to process client requests and generate dynamic web content. Servlet is mainly used to process or store data submitted by HTML forms, generate dynamic content, and manage status information under the stateless HTTP protocol.
76. Let’s talk about the architecture of Servlet.
The core interface that all Servlets must implement is javax.servlet.Servlet. Every Servlet must directly or indirectly implement this interface, or inherit javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet. Finally, Servlets use multiple threads to serve multiple requests in parallel.
77. What is a web application?
Web applications are dynamic extensions to the Web or application server. There are two types of web applications: presentation-oriented and service-oriented. Presentation-oriented web applications generate interactive web pages that contain a variety of markup languages and dynamic content in response to requests. Service-oriented Web applications implement the endpoints of Web services. Generally speaking, a Web application can be viewed as a collection of Servlets installed under a specific subset of the server's URL namespace.
78. How to know which client machine is requesting your Servlet?
The ServletRequest class can find out the IP address or host name of the client machine. The getRemoteAddr() method obtains the IP address of the client host, and getRemoteHost() obtains the host name.
79. What is the structure of HTTP response?
HTTP response consists of three parts:
Status Code (Status Code): describes the status of the response. Can be used to check whether the request was completed successfully. In the event that a request fails, the status code can be used to find out the reason for the failure. If the Servlet does not return a status code, the successful status code HttpServletResponse.SC_OK will be returned by default.
HTTP Header: They contain more information about the response. For example, the header can specify an expiration date when the response is considered expired, or it can specify an encoding format used to safely transmit entity content to the user. How to retrieve HTTP headers in Serlet see here.
Body: It contains the content of the response. It can contain HTML code, images, etc. The body consists of the data bytes transmitted in the HTTP message immediately following the header.
80. What is a cookie? What is the difference between session and cookie?
A cookie is a piece of information sent by the web server to the browser. The browser stores cookies for each web server in a local file. In the future, when the browser sends a request to a specific web server, it will also send all cookies stored for that server. The following lists the differences between session and cookie:
No matter what settings the client browser makes, session should work normally. The client can choose to disable cookies, but the session will still work because the client cannot disable the server-side session.
Sessions and cookies are also different in terms of the amount of data stored. Session can store any Java object, and cookie can only store String type objects.
81. How are JSP requests processed?
The browser must first request a page ending with the .jsp extension and initiate a JSP request. Then, the Web server reads the request and uses the JSP compiler to convert the JSP page into a Servlet class. It should be noted that the JSP file will only be compiled when the page is requested for the first time or the JSP file changes, and then the server calls the servlet class to handle the browser's request. Once the request execution is completed, the servlet will send the response to the client.
82. What are the definitions and benefits of encapsulation?
Encapsulation provides objects with the ability to hide internal characteristics and behaviors. An object provides methods that can be accessed by other objects to change its internal data. In Java, there are three modifiers: public, private and protected. Each modifier gives different access rights to other objects located in the same package or in different packages.
Listed below are some benefits of using encapsulation:
Protect the state inside the object by hiding its properties.
Improves the usability and maintainability of code because the behavior of objects can be individually changed or extended.
Prohibit bad interactions between objects to improve modularity.
Refer to this document for more details and examples about encapsulation.
Or:
First, use private to isolate the details of the class from the outside world, thereby hiding the data items and methods. The only way to access these data items and methods is through the class By itself, a class is eligible to call the resources it owns (methods, data item attributes, etc.). So the first benefit is that data security is improved.
The second is to hide isolation and only allow limited external access to the class. Developers can freely change the internal implementation of the class without modifying the programs that use the class. As long as the methods that can be called outside the class keep their external characteristics unchanged, the internal code can be changed freely to suit their needs, which facilitates division of labor.
The third is to improve the reusability of the code. After encapsulating it into a tool class, it can reduce many tedious steps.
83. What is the definition of abstraction? What is the difference between abstraction and encapsulation?
Abstraction is the step of separating ideas from concrete instances, thus creating classes based on their functionality rather than implementation details. Java supports the creation of abstract classes that only expose interfaces but do not contain method implementations. The main purpose of this abstraction technique is to separate the behavior of the class from the implementation details. Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of objects. Encapsulation, on the other hand, focuses on the details of an object's behavior. Encapsulation is generally achieved by hiding the internal state information of the object. Therefore, encapsulation can be regarded as a strategy used to provide abstraction.
Related recommendations:Getting started with java
The above is the detailed content of Sharing of common Java key interview questions. For more information, please follow other related articles on the PHP Chinese website!