Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common Java interview questions and answers?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "common Java interview questions and answers". In daily operation, I believe many people have doubts about common Java interview questions and answers. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions of "common Java interview questions and answers". Next, please follow the editor to study!

1. About the volatile keyword

1. Can I create an Volatile array?

You can create an array of volatile types in Java, but it's just a reference to the array, not the entire array. If you change the array that the reference points to, it will be protected by volatile, but if multiple threads change the elements of the array at the same time, the volatile identifier will not be able to protect you as before.

2. Can volatile turn a non-atomic operation into an atomic operation?

A typical example is having a member variable of type long in a class. If you know that the member variable will be accessed by multiple threads, such as counters, prices, etc., you'd better set it to volatile. Why? Because reading long type variables in Java is not atomic and needs to be divided into two steps, if one thread is modifying the value of the long variable, the other thread may only see half of that value (the first 32 bits). But reading and writing to a volatile-type long or double variable is atomic.

One practice is to modify long and double variables with volatile so that they can be read and written according to atomic types. Both double and long are 64-bit wide, so the reading of these two types is divided into two parts, first reading the first 32 bits, and then reading the remaining 32 bits, this process is not atomic, but the reading and writing of volatile-type long or double variables in Java is atomic. Another function of the volatile repair symbol is to provide a memory barrier (memory barrier), such as applications in distributed frameworks. To put it simply, before you write a volatile variable, the Java memory model inserts a write barrier (write barrier) and a read barrier (read barrier) before reading a volatile variable. This means that when you write a volatile field, it ensures that any thread can see the value you write, and that any numerical updates are visible to all threads before writing, because the memory barrier updates all other write values to the cache.

3. What guarantees do volatile type variables provide?

Volatile has two main functions: 1. Avoid rearranging instructions 2. Visibility guarantee. For example, JVM or JIT will reorder statements for better performance, but volatile type variables will not be reordered with other statements even without synchronous blocks. Volatile provides happens-before guarantees to ensure that changes made by one thread are visible to other threads. In some cases, volatile can also provide atomicity, such as reading 64-bit data types, such as long and double are not atomic (low 32-bit and high 32-bit), but double and long of volatile type are atomic.

II. About the set

1. Collections in Java and their inheritance relationships

Everyone should be familiar with the system of set, especially the principle of List,Map, which we often use.

2. The difference between the poll () method and the remove () method?

Both poll () and remove () fetch an element from the queue, but poll () returns null when it fails to get the element, but remove () throws an exception when it fails.

3. The difference between LinkedHashMap and PriorityQueue

PriorityQueue is a priority queue that ensures that the highest or lowest priority elements are always at the head of the queue, but the order maintained by LinkedHashMap is the order in which elements are inserted. When traversing a PriorityQueue, there is no order guarantee, but the LinkedHashMap lesson ensures that the traversal order is the order in which elements are inserted.

4. What is the difference between WeakHashMap and HashMap?

WeakHashMap works similar to normal HashMap, but uses weak references as key, meaning that when the key object does not have any references, the key/value will be recycled.

5. What is the difference between ArrayList and LinkedList?

The most obvious difference is that the underlying data structure of ArrrayList is an array, which supports random access, while the underlying data structure of LinkedList is a two-way cyclic linked list, which does not support random access. Using the subscript to access an element, the time complexity of ArrayList is O (1), while LinkedList is O (n).

6. What's the difference between ArrayList and Array?

Array can hold basic types and objects, while ArrayList can only hold objects.

The Array is the specified size, while the ArrayList size is fixed

7. ArrayList and HashMap default size?

In Java 7, the default size of ArrayList is 10 elements, and the default size of HashMap is 16 elements (must be a power of 2). This is the code snippet for the ArrayList and HashMap classes in Java 7.

Private static final int DEFAULT_CAPACITY = 10; / / from HashMap.java

JDK 7 static final int DEFAULT_INITIAL_CAPACITY = 1 fast, while the collection classes in java.util.concurrent are all fail-safe. When a change in the structure of the collection being traversed is detected, the Fail-fast iterator throws ConcurrentModificationException, while the fail-safe iterator never throws ConcurrentModificationException.

IV. About the date

1. Is SimpleDateFormat thread safe?

Unfortunately, all implementations of DateFormat, including SimpleDateFormat, are not thread-safe, so you should not use them in multithread programs unless they are used in external thread-safe environments, such as restricting SimpleDateFormat to ThreadLocal. If you don't, you may get an incorrect result when parsing or formatting the date. Therefore, in terms of all the practices of date and time processing, I strongly recommend the joda-time library.

2. How to format the date?

In Java, you can use the SimpleDateFormat class or the joda-time library to format dates. The DateFormat class allows you to format dates in a variety of popular formats. See the sample code in the answer, which demonstrates formatting dates into different formats, such as dd-MM-yyyy or ddMMyyyy.

5. About anomalies

1. Briefly describe the java exception system.

More information about the exception system can be seen than no one who does not understand the exception system.

2. What is an abnormal chain

For details, please refer to the vernacular exception mechanism above without explanation.

3. The difference between throw and throws

Throw is used to actively throw an instantiated object of the java.lang.Throwable class, which means that you can throw an Error or an Exception through the keyword throw, such as: throw new IllegalArgumentException ("size must be multiple of 2")

The role of throws is as part of the method declaration and signature, and the method is thrown with the corresponding exception so that the caller can handle it. In Java, any unhandled checked exception is forced to be declared in the throws clause.

IV. On serialization

The difference between Serializable and Externalizable in Java

The Serializable interface is an interface that serializes Java classes so that they can be transmitted over the network or keep their state on disk. It is the default serialization method embedded in JVM, which is costly, fragile, and insecure. Externalizable allows you to control the entire serialization process, specify a specific binary format, and add security mechanisms.

5. About JVM

1. JVM characteristics

Platform independence.

A very important feature of Java language is its platform independence. The use of Java virtual machine is the key to realize this feature. If a general high-level language is to run on different platforms, it needs to at least be compiled into different object code. After introducing the Java language virtual machine, the Java language does not need to be recompiled when it runs on different platforms. The Java language uses the pattern Java virtual machine to shield the information related to the specific platform, so that the Java language compiler only needs to generate the object code (bytecode) running on the Java virtual machine and can run on a variety of platforms without modification. When executing the bytecode, the Java virtual machine interprets the bytecode as the execution of machine instructions on the specific platform.

2. Explain the classloader briefly.

The class loader will generally ask you about the application scenarios of the four types of loaders and the parent delegation model.

3. Briefly describe the difference between heap and stack

In VM, heap and stack belong to different memory areas and are used for different purposes. The stack is often used to hold method frames and local variables, while objects are always allocated on the heap. The stack is usually smaller than the heap and is not shared among multiple threads, while the heap is shared by all threads of the entire JVM.

4. A brief description of JVM memory allocation

Basic data types are allocated on the stack than references to variables and objects.

Heap memory is used to hold objects and arrays created by new.

Class variables (static-decorated variables). The program allocates memory for the class variables in the heap when it is loaded, and the memory address in the heap is stored in the stack.

Instance variable: when you use the java keyword new, the system opens up in the heap is not necessarily continuous space allocated to variables, but according to the scattered heap memory address, the hash algorithm is converted into a long string of numbers to represent the "physical location" of the variable in the heap, the life cycle of the instance variable-when the reference of the instance variable is lost, it will be added to the recyclable "list" by GC (garbage collector). But not immediately freeing memory in the heap.

Local variable: by declaring in a method, or in a code snippet (such as a for loop), opening up memory in the stack when it is executed, and releasing memory as soon as the local variable is out of scope.

VI. Other

1. Is the big end or the small end used in java?

Several ways and characteristics of XML parsing

There are three parsing methods: DOM, SAX and PULL:

DOM: memory consumption: first read the xml documents into memory, and then use DOM API to access the tree structure and get the data. This is easy to write, but consumes a lot of memory. If the data is too large and the mobile phone is not powerful enough, the mobile phone may directly crash.

SAX: parsing is efficient, taking up less memory, based on event-driven: to put it more simply, it scans the document sequentially, notifies the event handler function when it comes to the beginning and end of the document (document), the beginning and end of the element (element), the end of the document (document), etc., and then continues the same scan until the end of the document.

PULL: similar to SAX, it is also event-driven. We can call its next () method to get the next parsing event (that is, start document, end document, start tag, end tag). When you are in an element, you can call the getAttributte () method of XmlPullParser to get the value of the attribute, or you can call its nextText () to get the value of this node.

2. JDK 1.7 characteristics

Although JDK 1.7 is not as big as JDK 5 and 8, there are still many new features, such as try-with-resource statements, so that you don't have to shut down manually when using streams or resources. Java shuts down automatically. The Fork-Join pool implements the Java version of Map-reduce to some extent. Allow String variables and text in Switch. The diamond operator () is used for type inference, and you no longer need to declare generics to the right of the variable declaration, so you can write code that is more readable and concise.

3. JDK 1.8 characteristics

Java 8 is a pioneering version of Java. Here are five main features of JDK 8:

Lambda expressions that allow anonymous functions to be passed like objects

Stream API, which makes full use of modern multicore CPU, can write very concise code.

Date and Time API, finally, have a stable and simple date and time library for you to use.

Extension methods, now there can be static, default methods in the interface.

Repeat comments, and now you can use the same comments multiple times on the same type.

4. What's the difference between Maven and ANT?

Although both are build tools for creating Java applications, Maven does more, providing a standard Java project structure based on the concept of "convention over configuration" while automatically managing dependencies (JAR files that depend on the application) for the application.

JDBC best practices

Priority is given to bulk operations to insert and update data

Use PreparedStatement to avoid SQL vulnerabilities

Use data connection pooling

Get the result set by column name

Best practices for IO Operation

Use buffered IO classes and do not read bytes or characters separately

Use NIO and NIO 2 or AIO instead of BIO

Close the stream in finally

Use memory-mapped files to get faster IO

At this point, the study of "what are the common Java interview questions and answers" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report