国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaInterview questions Compilation of common Java interview questions

Compilation of common Java interview questions

Nov 29, 2019 pm 01:55 PM
java

Compilation of common Java interview questions

What are the characteristics of object-oriented?

The so-called encapsulation is to encapsulate objective things into abstract objects Class, and the class can allow its own data and methods to be operated only by trusted classes or objects, and hide information from untrusted ones. Encapsulation is one of the characteristics of object-oriented and the main characteristic of the concepts of objects and classes. (Recommended study: java common interview questions)

Inheritance means that the subclass obtains the attributes and methods of the parent class. For example, if a dog is a type of animal, it can also be said that it inherits the characteristics of the animal, or that the dog is a subclass of the animal.

Polymorphism means that a method can only have one name, but it can have many forms. That is, multiple methods with the same name can be defined in the program, which is described by "one interface, multiple methods". You can pass Method parameters and type references

Five principles: Single Responsibility Principle SRP Open and Closed Principle OCP Replacement Principle LSP Dependency Principle DIP Interface Separation Principle ISP

Member variables and local variables The difference

* A: Different positions in the class

* Member variables: outside the methods in the class

* Local variables : In the method definition or method declaration

* B: Different locations in the memory

* Member variables: In the heap memory (member variables belong to objects, objects into heap memory)

* Local variables: in stack memory (local variables belong to methods, methods are pushed into stack memory)

* C: different life cycles

* Member variables: exist when the object is created and disappear when the object disappears

* Local variables: exist when the method is called and disappear when the method is called

* D: Different initialization values

* Member variables: have default initialization values

* Local variables: no default initialization values, must be defined, assigned, and then can be used.

The difference between static variables and member variables

* Static variables are also called class variables. Member variables are also called object variables

* A: Different ownership

* Static variables belong to classes, so they are also called class variables

* Member variables belong to objects, so they are also called instance variables (object variables)

* B: Different locations in memory

* Static variables are stored in the static area of ??the method area

* Member variables are stored in the heap memory

* C: Memory appearance time is different

* Static variables are loaded as the class is loaded, and disappear as the class disappears

* Member variables follow the object's It exists when it is created and disappears when the object disappears

* D: Different calls

* Static variables can be called through class names or through objects

* Member variables can only be called through the object name

The difference and application of this and super

* A: What do this and super stand for

* this: represents the reference of the current object, whoever calls me, I will represent that person

* super: represents the reference of the parent class of the current object

* B: The difference between the use of this and super

* a: Calling member variables

* this. Member variables call member variables of this class or of the parent class Member variable

* super. Member variable calls the member variable of the parent class

* b: Calls the constructor method

* this(...) calls the constructor method of this class

* super(...) calls the constructor method of the parent class

* c: calls the member method

* this. The member method calls the member method of this class, also You can call the method of the parent class

*super.Member method calls the member method of the parent class

What are the methods of sorting? Please list the

sorting methods: insertion sort (direct insertion sort, Hill sort), exchange sort (bubble sort, quick sort), selection sort (direct selection sort, heap sort), Merge sort, distribution sort (box sort, radix sort)

Pseudo code of quick sort.

The difference between String, StringBuffer and StringBuilder.

The length of String is immutable;

The length of StringBuffer is variable. If you frequently operate on the content in the string, especially if the content is When modifying, use StringBuffer. If String is needed in the end, use StringBuffer's toString() method; thread safety;

StringBuilder is starting from JDK 5 and adds an equivalent method for single thread use to the StringBuffer class. class; you should generally use the StringBuilder class in preference because it supports all the same operations, but is faster because it does not perform synchronization.

The difference between Overload and Override. Can an Overloaded method change the type of return value?

Answer: Method overriding Overriding and overloading Overloading are different manifestations of Java polymorphism.

Overriding is a manifestation of polymorphism between parent classes and subclasses, and overloading is a manifestation of polymorphism in a class. If a method defined in a subclass has the same name and parameters as its parent class, we say the method is overriding.

When an object of a subclass uses this method, the definition in the subclass will be called. For it, the definition in the parent class seems to be "shielded". If multiple methods with the same name are defined in a class, and they have different number of parameters or different parameter types, it is called method overloading. Overloaded method can change the type of return value.

What is the difference between final and finally?

Answer: final: modifier (keyword); if a class is declared final, it means that it cannot Derived new subclasses cannot be inherited as parent classes, so a class cannot be declared both abstract and final; declaring variables or methods as final ensures that they will not be changed during use. ; Variables declared as final must be given an initial value when declared, and can only be read in subsequent references and cannot be modified; methods declared as final can also only be used and cannot be overloaded.

finally: Provide a finally block to perform any cleanup operations during exception handling; if an exception is thrown, the matching catch clause will be executed, and then control will enter the finally block (if any ).

Several common operating abnormalities.

java.lang.nullpointerexception (null pointer exception)

java.lang.classnotfoundexception (the specified class does not exist)

java.lang.arithmeticexception (mathematical Operation exception)

java.lang.arrayindexoutofboundsexception (array subscript out-of-bounds exception)

IOException (input and output exception)

Two common problems with array operations are out-of-bounds and empty Pointer

* A:Case demonstration

* a:ArrayIndexOutOfBoundsException: Array index out of bounds exception

* Reason: You accessed a non-existent index.

* b: NullPointerException: Null pointer exception

* Reason: The array no longer points to the heap memory. And you also use array names to access elements.

  * int[] arr = {1,2,3};
  * arr = null;
  * System.out.println(arr[0]);

How does JAVA language handle exceptions? What do the keywords: throws, throw, try, catch, and finally mean? Can exception be thrown in try block?

Answer: Java handles exceptions through object-oriented methods, classifies various exceptions, and provides a good interface.

In Java, each exception is an object, which is an instance of the Throwable class or other subclasses. When an exception occurs in a method, an exception object is thrown. The object contains exception information. The method of calling this object can catch the exception and handle it.

Java's exception handling is implemented through 5 keywords: try, catch, throw, throws and finally. Generally, try is used to execute a program. If an exception occurs, the system will throw an exception. At this time, you can catch it by its type, or finally by the default handler. to handle.

Use try to specify a program that prevents all "exceptions". Immediately after the try program, a catch clause should be included to specify the type of "exception" you want to catch.

Thethrow statement is used to explicitly throw an "exception".

throws is used to indicate various "exceptions" that a member function may throw.

Finally ensures that a piece of code is executed no matter what "exception" occurs.

You can write a try statement outside a member function call, and write another try statement inside the member function to protect other code. Whenever a try statement is encountered, the "exception" frame is placed on the stack until all try statements are completed.

If the next level try statement does not handle a certain "exception", the stack will expand until it encounters a try statement that handles this "exception".

When the server receives the form data submitted by the user, does it call the Servlet's doGet() or doPost() method?

Answer: The

element of HTML has a method attribute, which is used to specify the method of submitting the form. Its value can be get or post.

Our custom Servlet will generally override one or both of the doGet() or doPost() methods. If it is a GET request, it will call the doGet() method. If it is a POST request, it will call doPost. () method, then why is this happening?

Our custom Servlet usually inherits from HttpServlet, HttpServlet inherits from GenericServlet and overrides the service() method, which is defined in the Servlet interface.

The service() method rewritten by HttpServlet will first obtain the method requested by the user, and then call doGet(), doPost(), doPut(), doDelete() and other methods according to the request method. If you are customizing the Servlet If these methods are overridden in , then the overwritten (customized) methods will obviously be called, which is obviously an application of the template method pattern (if you don't understand, please refer to Chapter 37 of the book "Java and Patterns") .

Of course, the service() method can also be directly rewritten in a custom Servlet, so no matter what kind of request it is, it can be processed through your own code, which is more suitable for scenarios where the request method is not distinguished.

What is the difference between abstract class and interface?

Interface is a variant of abstract class, and all methods in the interface are abstract. An abstract class is a class that declares the existence of a method without implementing it.

Interfaces can have multiple inheritance, but abstract classes cannot.

Interfaces define methods but cannot implement them, while abstract classes can implement some methods.

The basic data type in the interface is static but the abstract image is not.

Memory leak and memory overflow?

Memory leak: It means that after the application applies for memory, it cannot release the memory space it has applied for. The harm of a memory leak can be ignored, but if it is allowed to develop, it will lead to memory overflow.

For example: after reading the file, the stream must be closed in time and the database connection must be released.

Memory overflow: It means that when the application applies for memory, there is no final memory space for it to use.

For example: We import large batches of data in the project using segmented batch submission.

What is thread synchronization?

1. The purpose of thread synchronization is to protect resources from being damaged when multiple threads query a resource.

2. The thread synchronization method is implemented through locks. Each object has only one lock. This lock is associated with a specific object. Once a thread acquires the object lock, other threads accessing the object You can no longer access other non-synchronized methods of the object.

3. For static synchronization methods, the lock is for this class, and the lock object is the Class object of this class. The locks of static and non-static methods do not interfere with each other. When a thread acquires a lock and accesses a synchronized method on another object in a synchronized method, it will acquire the two object locks.

4. For synchronization, it is key to always be aware of which object to synchronize on.

5. When writing thread-safe classes, you need to always pay attention to making correct judgments on the logic and safety of multiple threads competing to access resources, analyze "atomic" operations, and ensure that other operations during atomic operations are The thread cannot access the competing resource.

6. When multiple threads are waiting for an object lock, the thread that has not acquired the lock will be blocked.

7. Deadlock is caused by threads waiting for each other to lock. The probability of occurrence in practice is very small. If I really ask you to write a deadlock program, it may not work, haha. However, once a deadlock occurs in the program, the program will die.

Understanding of multi-threading?

The same thing, done by different people, is multi-threading.

When cooking in the cafeteria, one person is single-threaded. Opening N windows and N people eating at the same time is multi-threading.

The basic concept of threads, the basic status of threads, and the relationship between states Relationship:

Thread refers to an execution unit that can execute program code during program execution. Each program has at least one thread, which is the program itself. Threads in Java have four states: running, ready, suspended, and ended.

What collections are there?

List features: elements are put in order, elements can be repeated

Map features: elements are stored in key-value pairs, no putting order

Set features: elements There is no putting order, and elements cannot be repeated (note: although there is no putting order for elements, the position of the element in the set is determined by the HashCode of the element, and its position is actually fixed)

The List interface has three Implementation classes: LinkedList, ArrayList, Vector

LinkedList: The bottom layer is implemented based on a linked list. The linked list memory is scattered. Each element stores its own memory address and also stores the address of the next element. Linked lists are fast to add and delete, but slow to search.

The difference between ArrayList and Vector: ArrayList is non-thread-safe and has high efficiency; Vector is based on thread-safety and has low efficiency

The Set interface has two implementation classes: HashSet (the bottom layer is implemented by HashMap), LinkedHashSet

SortedSet interface has an implementation class: TreeSet (the bottom layer is implemented by balanced binary tree)

The Query interface has an implementation class: LinkList

The Map interface has three implementation classes: HashMap, HashTable, LinkeHashMap

HashMap is not thread-safe, efficient, and supports null; HashTable is thread-safe, inefficient, and does not support null

SortedMap has an implementation class: TreeMap

In fact, the most important thing is that list is used to process sequences, while set is used to process sets. Map is the basic class that stores key-value pairs

File reading and writing:

File Reader class and FileWriter class inherit from Reader class and Writer class respectively. The FileReader class is used to read files, and the File Writer class is used to write data to files. Before using these two types, you must call their construction methods to create the corresponding objects, and then call the corresponding read() or write() method.

The above is the detailed content of Compilation of common Java interview questions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Java Optional example Java Optional example Jul 12, 2025 am 02:55 AM

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

How to fix java.io.NotSerializableException? How to fix java.io.NotSerializableException? Jul 12, 2025 am 03:07 AM

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

Java method references explained Java method references explained Jul 12, 2025 am 02:59 AM

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How to parse JSON in Java? How to parse JSON in Java? Jul 11, 2025 am 02:18 AM

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.

See all articles