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 10 difficult Java interview questions?

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

Share

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

This article introduces the knowledge of "what are 10 difficult Java interview questions". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Why are waits and notifications declared in the Object class instead of Thread?

A thorny Java question, how can you answer this question if you didn't design the Java programming language? Common sense and in-depth understanding of Java programming can help answer interview questions about this thorny core aspect of Java.

Why wait,notify and notifyAll are defined in the Object class instead of the Thread class

This is a famous Java interview question, which may be encountered in an interview with a senior Java developer with 2-4 years of experience.

The good thing about this question is that it reflects the interviewer's understanding of the mechanism of waiting for notification and whether he has a clear understanding of the subject. Like the question of why multiple inheritance is not supported in Java or why String is final in Java, there may be multiple answers to this question.

Everyone can give some reason why wait and notify methods are defined in the Object class. From my interview experience, wait and nofity are still the most confused for most Java programmers, especially 2-3-year-old developers who will be confused if they ask to use wait and notify. So, if you go to a Java interview, make sure you have a good understanding of wait and notify mechanisms, and that you can easily write code in wait and learn about notification mechanisms such as producer-consumer questions or implementing blocking queues.

Why waits and notifications need to be called from synchronous blocks or methods, as well as the differences between wait,sleep and yield methods in Java, will be interesting if you haven't read them. Why do wait,notify and notifyAll belong to the Object class? Why shouldn't they be in the Thread class? Here are some ideas that I think make sense:

1) wait and notify are not only common methods or synchronization tools, but more importantly, they are communication mechanisms between two threads in Java. For language designers, if the communication mechanism cannot be implemented through the Java keyword, such as synchronized, while ensuring that the mechanism is available for each object, then the Object class is the correct declaration location. Remember that synchronization and waiting for notifications are two different areas, and don't think of them as the same or related. Synchronization provides mutual exclusion and ensures thread safety of the Java class, while wait and notify are the communication mechanisms between the two threads.

2) every object can be locked, which is another reason to declare wait and notify in the Object class instead of the Thread class.

3) in Java, in order to enter the critical section of the code, threads need to lock and wait for the lock, they do not know which thread holds the lock, but just know that the lock is held by a thread, and they should wait to acquire the lock, instead of knowing which thread is in the synchronization block and asking them to release the lock.

4) Java is the idea of monitor based on Hoare (http://en.wikipedia.org/wiki/.... In Java, all objects have a monitor.

The thread is waiting on the monitor, and to perform the wait, we need two parameters:

One thread

A monitor (any object)

In Java design, a thread cannot be specified, it is always the thread running the current code. However, we can specify a monitor (this is what we call a wait object). This is a good design, because if we can make any other thread wait on the desired monitor, it will lead to "intrusion" and difficulties in designing concurrent programs. Keep in mind that in Java, all operations that break into the execution of another thread are deprecated (for example, the stop method).

two。 Why is multiple inheritance not supported in Java?

I find this Java core question difficult to answer because your answer may not satisfy the interviewer. In most cases, the interviewer is looking for key points in the answer, and if you mention these key points, the interviewer will be very happy. The key to answering this thorny question in Java is to prepare the relevant topics to deal with all possible follow-up questions.

This is a very classic question, similar to why String is immutable in Java; the similarity between the two questions is that they are mainly caused by the design decisions of Java creators.

Why Java does not support multiple inheritance, you can consider the following two points:

1) the first reason is around diamonds? Given the ambiguity caused by the problem of shape inheritance, consider that a class A has a foo () method, and then B and C derive from An and have their own implementation of foo (). Now that Class D uses multiple inheritance derived from B and C, if we only refer to foo (), the compiler will not be able to decide which foo () it should call. This is also called the Diamond problem because the structure of this inheritance scheme is similar to a diamond, as shown in the following figure:

A foo () /\ / C foo ()\ /\ / D foo ()

Even if we remove the top class An of the diamond and allow multiple inheritance, we will see the ambiguous side of the problem. If you tell the interviewer this reason, he will ask why C++ can support multiple inheritance while Java can't. Well, in this case, I will try to explain to him the second reason I give below, it is not because of technical difficulty, but because more maintainability and clearer design are driving factors, although this can only be confirmed by Java speech designers, we are just speculating. Wikipedia links have some good explanations for how different language address problems arise because of the diamond problem when using multiple inheritance.

2) the second and more compelling reason for me is that multiple inheritance does complicate the design and cause problems in the process of transformation, constructor linking, and so on. Assuming that there are not many situations in which you need multiple inheritance, for the sake of simplicity, it would be wise to omit it. In addition, Java can avoid this ambiguity by using interfaces to support single inheritance. Because the interface has only method declarations and does not provide any implementation, there is only one implementation of a particular method, so there is no ambiguity.

3. Why does Java not support operator overloading?

Another similarly intractable Java problem. Why does C++ support operator overloading but not Java? One might say that the + operator has been overloaded for string concatenation in Java, so don't be fooled by these arguments.

Unlike C++, Java does not support operator overloading. Java does not provide programmers with free standard arithmetic operator overloading, such as +, -, *, and /. If you have used cached codes before, Java has a lot less functionality than C++. For example, Java does not support multiple inheritance, there is no pointer in Java, and there is no reference passing in Java. Another similar question is about whether Java is passed by reference, which is mainly represented by whether Java passes parameters by value or reference. Although I don't know the real reason behind it, I think there is some truth in why Java doesn't support operator overloading.

1) simplicity and clarity. Clarity is one of the goals of Java designers. Designers don't just want to copy the language, but want to have a clear, truly object-oriented language. Adding operator overloading will certainly make the design more complex than without it, and it can lead to a more complex compiler, or slow down JVM, because it requires additional work to identify the actual meaning of operators and reduce opportunities for optimization to ensure operator behavior in Java.

2) avoid programming errors. Java does not allow user-defined operator overloading, because allowing programmers to overload operators will give multiple meanings to the same operator, which will steepen any developer's learning curve and make things more confusing. It has been observed that programming errors increase when the language supports operator overloading, increasing development and delivery time. Since Java and JVM have assumed the responsibility of most developers, such as when managing memory by providing a garbage collector, it doesn't make much sense because this feature increases the chance of contaminating the code and becomes the source of programming errors.

3) JVM complexity. From a JVM perspective, supporting operator overloading makes the problem more difficult. The same thing can be achieved by using method overloading in a more intuitive and cleaner way, so it makes sense not to support operator overloading in Java. Compared to the relatively simple JVM, a complex JVM may cause the JVM to be slower and reduce the chance of optimizing the code to ensure the certainty of operator behavior in the Java.

4) make it easier for development tools to handle. This is another benefit that operator overloading is not supported in Java. Omitting operator overloading makes the language easier to handle, which in turn makes it easier to develop tools that deal with the language, such as IDE or refactoring tools. The refactoring tools in Java are much better than C++.

4. Why is String immutable in Java?

My favorite Java interview question is tricky, but it is also very useful. Some interviewers often ask why String is final in Java.

Strings are immutable in Java because String objects are cached in the String pool. Because cached strings are shared among multiple customers, there is always a risk that the operation of one customer will affect all other customers. For example, if a piece of code changes the value of String "Test" to "TEST", all other customers will see the value as well. Because the caching performance of String objects is an important aspect, this risk is avoided by making the String class immutable.

At the same time, String is final, so no one can break the immutability, caching, hash calculation of String classes by extending and overriding behavior. Another reason why String classes are immutable may be due to HashMap.

Because it is popular to use strings as HashMap keys. What is important for key values is that they are immutable so that they can be used to retrieve value objects stored in HashMap. Because HashMap works as a hash, you need to have the same value in order to work properly. If the contents of the String are modified after insertion, the mutable String will generate two different hash codes during insertion and retrieval, possibly losing the value object in the Map.

If you are an Indian cricket fan, you may be able to relate to my next sentence. The string is the VVS Laxman of Java, which is a very special class. I haven't seen a Java program written in String yet. This is why a full understanding of String is important for Java developers.

String as a data type, the importance and popularity of transfer objects and middleman roles also make this question very common in Java interviews.

Why String is immutable in Java is one of the most frequently asked string access questions in Java. It first discusses what is String in String,Java and how it is different from String in C and C++, and then turns to what are immutable objects in Java, what are the benefits of immutable objects, why they should be used, and which scenarios should be used. This question sometimes asks, "Why is String final in Java?" In similar instructions, if you are preparing for a Java interview, I suggest you take a look at the Java programming interview public book, which is an excellent resource for advanced and intermediate Java programmers. It contains questions from all important Java topics, including multithreading, collections, GC,JVM internals, as well as Spring and Hibernate frameworks.

As I said, there may be many possible answers to this question, and the only designer of the String class can safely answer it. I looked forward to some clues in Joshua Bloch's Effective Java book, but he didn't mention it either. I think the following points explain why String classes are immutable or final in Java:

1) imagine that string pooling does not make strings immutable, it is impossible, because in the case of string pooling, a string object / literal, such as "Test", has been referenced by many reference variables, so if any one of them changes the value, the other parameters will be automatically affected, that is, assuming

String A = "Test"; String B = "Test"

Now the string B calls "Test" .toUpperCase (), changing the same object to "TEST", so An is also "TEST", which is not the desired result.

The following figure shows how to create strings in heap memory and string pools.

2) the string has been widely used as a parameter of many Java classes, for example, in order to open a network connection, you can pass the host name and port number as a string, you can pass the database URL as a string to open the database connection, and you can open any file in Java by passing the file name as a parameter to the File Igamo class. If the String is not immutable, this can lead to a serious security threat. I mean, someone can access any file he has permission to authorize, and then deliberately or accidentally change the file name and gain access to that file. Because of immutability, you don't have to worry about this threat. This reason also explains why String is final in Java by enabling java.lang.String final,Java designers to ensure that no one overrides any behavior of the String class.

3) because String is immutable, it can safely share many threads, which is very important for multithreaded programming. It also avoids synchronization problems in Java, and invariance makes String instances thread-safe in Java, which means you don't need to synchronize String operations externally. Another important point about String is the memory leak caused by intercepting the string SubString, which is not a thread-related issue, but it is also a matter of note.

4) another reason why String is immutable in Java is that it allows String to cache its hash code, and immutable String in Java caches its hash code and does not recalculate every time the hashcode method of String is called, which makes its use of the HashMap key in HashMap in Java very fast. In short, because String is immutable, no one can change its contents after creation, which ensures that String's hashCode is the same when called multiple times.

5) the absolute most important reason why String is immutable is that it is used by the class loading mechanism, so it has profound and basic security considerations. If String is mutable, the request to load java.io.Writer may have been changed to load mil.vogoon.DiskErasingWriter. Security and string pooling are the main reasons for making strings immutable. By the way, the above reason is a good answer to another Java interview question: "Why is String final in Java?" To be immutable, you must be final so that your subclasses do not break immutability. What do you think?

5. Why is the char array better for storing passwords than String in Java?

Another thorny Java question based on String, which I believe only a few Java programmers can answer correctly. This is a really difficult core Java interview question and requires a solid knowledge of String to answer it.

This is a question I asked a friend of mine in a recent Java interview. He is being interviewed for the position of technical supervisor and has more than 6 years of experience. If you haven't encountered this before, character arrays and strings can be used to store text data, but it's hard to choose one instead of the other. But as my friend said, any question related to String must have some clues about the special properties of the string, such as invariance, which he uses to convince the interviewer. Here, we will explore some of the reasons why you should use char [] to store passwords instead of String.

String: 1) because the string is immutable in Java, if you store the password as plain text, it will be available in memory until the garbage collector clears it. And for reusability, there will be String in the string pool, which is likely to remain in memory for a long time, posing a security threat.

Because anyone with access to the memory dump can find the password in clear text, this is another reason that you should always use an encrypted password instead of plain text. Because the string is immutable, you cannot change the contents of the string, because any change will result in a new string, and if you use char [], you can set all elements to blank or zero. Therefore, storing passwords in character arrays can significantly reduce the security risk of stealing passwords.

2) Java itself recommends using JPasswordField's getPassword () method, which returns a char [] and a deprecated getTex () method, which returns the password in clear text for security reasons. Follow the advice of the Java team and stick to the standard instead of opposing it.

3) when using String, there is always a risk of printing plain text in a log file or console, but if you use Array, the contents of the array will not be printed but its memory location will be printed. Although it is not a real reason, it still makes sense.

String strPassword = "Unknown"; char [] charPassword = new char [] {'ULTHINGRAPHY [] System.out.println ("character password:" + strPassword); System.out.println ("character password:" + charPassword)

Output

String password: Unknown

Character password: [C @ 110b053

I also recommend using a hash or encrypted password instead of plain text and clearing it from memory as soon as the validation is complete. Therefore, in Java, using character arrays to store passwords is a better choice than strings. Although using char [] is not enough, you also need to erase the content to be more secure.

6. How do I use double-checked locking to create a thread-safe singleton in Java?

Difficult core Java interview questions. This Java question is also often asked: what is a thread-safe singleton and how do you create it. Well, in versions prior to Java 5, when creating a singleton Singleton with double-checked locks, if multiple threads tried to create Singleton instances at the same time, multiple Singleton instances might be created. Starting with Java 5, it's easy to use Enum to create a thread-safe Singleton. But if the interviewer insists on double-checking locking, then you have to write code for them. Remember to use the volatile variable.

Why enumerating singles is better in Java

Enumerating singletons is a new way to implement singleton patterns in Java using an instance. Although the singleton pattern in Java has existed for a long time, enumerating singletons is a relatively new concept, starting with Java5 after introducing Enum as a keyword and function. This article is somewhat relevant to the previous content about Singleton, which discussed common questions in interviews about Singleton mode, as well as 10 examples of Java enumerations, in which we saw how generic enumerations can. This article is about why we should use Eeame as a singleton in Java, what advantages it has over the traditional singleton approach, and so on.

Java enumeration and singleton mode

The enumerated singleton pattern in Java uses enumeration to implement the singleton pattern in Java. Singleton pattern has been used in Java for a long time, but it is not long to use enumerated types to create singleton pattern. If you are interested, you can learn about the builder design pattern and the decorator design pattern.

1) enumerated singles are easy to write

This is by far the biggest advantage, and if you've been writing singletons before Java 5, you know, even if double-check locks, you can still have multiple instances. Although this problem has been solved through improvements to the Java memory model, with volatile type variables starting with Java 5, it is still tricky for many beginners to write. Compared with synchronous double-check locking, enumerating singletons is too simple. If you don't believe it, compare the following code for traditional double-check locking singletons and enumerating singletons:

A single example of using enumerations in Java

This is the way we usually declare singletons of enumerations, which may contain instance variables and instance methods, but for simplicity, I don't use any instance methods, just note that if you are using an instance method and the method can change the state of the object, you need to ensure that the method is thread-safe. By default, it is thread-safe to create enumerated instances, but it is the programmer's responsibility whether any other method on the Enum is thread-safe.

/ * Singleton pattern example using Java enumeration * / public enum EasySingleton {INSTANCE;}

You can handle it through EasySingleton.INSTANCE, which is much easier than calling the getInstance () method on a singleton.

A single example with double check locking

The following code is an example of double-checked locking in singleton mode, where the getInstance () method checks twice to see if INSTANCE is empty, which is why it is called double-checked locking mode. Keep in mind that double-checked locking is the Java5 before the agent, but it should work perfectly due to the interference of volatile variables in the Java5 memory model.

/ * Singleton mode example, double lock check * / public class DoubleCheckedLockingSingleton {private volatile DoubleCheckedLockingSingleton INSTANCE; private DoubleCheckedLockingSingleton () {} public DoubleCheckedLockingSingleton getInstance () {if (INSTANCE = = null) {synchronized (DoubleCheckedLockingSingleton.class) {/ / double checking Singleton instance if (INSTANCE = = null) {INSTANCE = new DoubleCheckedLockingSingleton () } return INSTANCE;}}

You can call DoubleCheckedLockingSingleton.getInstance () to get access to this singleton class.

For now, just look at the amount of code required to create thread-safe Singleton with delayed loading. Using the enumerated singleton pattern, you can have this pattern on one line because creating enumerated instances is thread-safe and is done by JVM.

One might argue that there are better ways to write Singleton than double-check locking methods, but each method has its own advantages and disadvantages, like my favorite static field Singleton created when the class is loaded, as shown below, but keep in mind that this is not a delayed loading singleton:

The singleton pattern uses the static factory method

This is one of my favorite ways to influence the Singleton schema in Java because the Singleton instance is static and the last variable is initialized when the class is first loaded into memory, so instance creation is inherently thread-safe.

/ * * Singleton pattern example and static factory method * / public class Singleton {/ / initailzed during class loading private static final Singleton INSTANCE = new Singleton (); / / to prevent creating another instance of Singleton private Singleton () {} public static Singleton getSingleton () {return INSTANCE;}}

You can call Singleton.getSingleton () to get access to this class.

2) enumerate singletons to handle serialization by themselves

Another problem with traditional singletons is that once serializable interfaces are implemented, they are no longer Singleton, because the readObject () method always returns a new instance, just like the constructor in Java. Avoid this by using the readResolve () method by replacing Singeton in the following example:

/ / readResolve to prevent another instance of Singleton private Object readResolve () {return INSTANCE;}

If the Singleton class maintains its internal state, this becomes more complicated because you need to mark it as transient (not serialized), but with an enumeration singleton, serialization is done by JVM.

3) it is thread safe to create enumerated instances

As mentioned in point 1, because the creation of Enum instances is thread-safe by default, you don't have to worry about double-checked locking.

In summary, enumerating singleton patterns in two lines of code is the best way to create Singleton in the world after Java 5, while ensuring serialization and thread safety. You can still use other popular methods, such as you feel better, welcome to discuss.

7. When writing a Java program, how do I create a deadlock in Java and fix it?

One of the classic but core Java interview questions.

If you are not involved in the coding of multithreaded concurrent Java applications, you may fail.

How to avoid Java thread deadlock?

How to avoid deadlocks in Java? It is one of the hot topics in Java interviews, and it is also one of the most important tastes in multithreaded programming. It is easy to be asked when recruiting senior programmers, and there are many follow-up questions. Although the problem seems very basic, most Java developers will get into trouble once you start digging into it.

Interview questions always say, "what is a deadlock?" Start

When two or more threads are waiting for each other to release the required resources (lock) and fall into an infinite wait is a deadlock. It occurs only in the case of multitasking or multithreading.

How to detect deadlocks in Java?

Although there are many answers to this, my version is that first I look at the code, if I see a nested synchronization block, or call other synchronization methods from a synchronized method, or try to acquire locks on different objects, if developers are not very careful, it is easy to cause deadlocks.

Another way is to find the application when it is actually locked and try to take a thread dump. In Linux, you can do this with the kill-3 command, which will print the status of all threads in the application log file, and you can see which thread is locked on which thread object.

You can use tools such as the fastthread.io website to analyze the thread dump, which allows you to upload the thread dump and analyze it.

Another way is to use jConsole or VisualVM, which will show which threads are locked and which objects are locked.

If you are interested in learning about troubleshooting tools and analyzing thread dumps, I suggest you take a look at Uriah Levy's "analyzing Java thread dumps" course on multiple Vision (PluraIsight). Designed to learn more about Java thread dumps and to be familiar with other popular advanced troubleshooting tools.

Write a Java program that will lead to deadlocks?

Once you have answered the previous question, they may ask you to write code, which will lead to a Java deadlock.

This is one of my versions.

/ * the Java program creates a deadlock by forcing a loop to wait. * * / public class DeadLockDemo {/ * * this method requests two locks, the first string, and then the integer * / public void method1 () {synchronized (String.class) {System.out.println ("Aquired lock on String.class object") Synchronized (Integer.class) {System.out.println ("Aquired lock on Integer.class object");} / * * this method also requests the same two locks, but in exactly * the opposite order, that is, the integer first, and then the string. * if one thread holds a string lock then this will result in a potential deadlock * and others hold integer locks that they wait for each other forever. * / public void method2 () {synchronized (Integer.class) {System.out.println ("Aquired lock on Integer.class object"); synchronized (String.class) {System.out.println ("Aquired lock on String.class object");}}

If both method1 () and method2 () are called by two or more threads, there is a possibility of deadlock, because if thread 1 acquires a lock on the Sting object while executing method1 (), thread 2 acquires the lock on the Integer object while executing method2 (), waiting for each other to release the locks on Integer and String to continue with one step, but this will never happen.

This figure accurately demonstrates our program, where one thread holds locks on one object and waits for other object locks held by other threads.

As you can see, Thread1 needs the lock on Object2 held by Thread2, while Thread2 wants to get the lock on Object1 held by Thread1. Because no thread is willing to give up, there is a deadlock and the Java program is stuck.

The idea is that you should know the right way to use common concurrency patterns, and if you are not familiar with these patterns, then Jose Paumard's "common Java patterns applied to concurrency and multithreading" is a good starting point for learning.

How to avoid deadlocks in Java?

Now the interviewer comes to the last part, in my opinion, one of the most important parts; how to fix the deadlock in the code? Or how to avoid deadlocks in Java?

If you take a closer look at the above code, you may have found that the real cause of the deadlock is not multiple threads, but the way they request the lock, and if you provide orderly access, the problem will be resolved.

Here is my fix version, which avoids deadlocks without preemption by avoiding loop waits, which is one of the four conditions that require deadlocks.

Both public class DeadLockFixed {/ * methods now request locks in the same order, first with integers and then with String. * you can also do the reverse, for example, the first string, and then the integer, * as long as both methods request locking, both can solve the problem * in the same order. * / public void method1 () {synchronized (Integer.class) {System.out.println ("Aquired lock on Integer.class object"); synchronized (String.class) {System.out.println ("Aquired lock on String.class object") } public void method2 () {synchronized (Integer.class) {System.out.println ("Aquired lock on Integer.class object"); synchronized (String.class) {System.out.println ("Aquired lock on String.class object");}}

There are no deadlocks now because both methods access locks on the text of the Integer and String classes in the same order. Therefore, if thread An acquires a lock on the Integer object, thread B will not continue until thread A releases the Integer lock, and even if thread B holds the String lock, thread A will not be blocked, because now thread B does not expect thread A to release the Integer lock to continue.

8. What happens if your Serializable class contains a non-serializable member? How did you solve it?

Any attempt to serialize this class will fail because of NotSerializableException, but this can be easily resolved by setting a transient (trancient) variable for static in Java.

Frequently asked questions related to Java serialization

Java serialization is an important concept, but it is rarely used as a persistence solution, and developers mostly ignore Java serialization API. In my experience, Java serialization is a very important topic in any Java core content interview. In almost all online interviews, I have encountered one or two Java serialization questions. I have seen an interview, and after asking a few questions about serialization, candidates begin to feel uncomfortable because of lack of experience in this area. They do not know how to serialize objects in Java, or they are not familiar with any Java examples to explain serialization, forgetting things such as how serialization works in Java, what is tagged interfaces, what is the purpose of tagging interfaces, the differences between transient and variable variables, how many methods are available for serializable interfaces, what is the difference between Serializable and Externalizable in Java, or after the introduction of annotations Why not use @ Serializable annotations or replace the Serializalbe interface.

In this article, we will ask questions from beginners and high levels, which will benefit both novice and senior developers with many years of Java development experience.

10 interview questions about Java serialization

Most commercial projects use database or memory-mapped files or just plain files to meet persistence requirements, and only a few projects rely on the serialization process in Java. In any case, this article is not a Java serialization tutorial or how to serialize objects in Java, but about the serialization mechanism and serialization API interview questions, it is worth reading before any Java interview so as not to surprise yourself with some unknown content.

For those unfamiliar with Java serialization, Java serialization is the process of serializing objects in Java by storing the state of the object in a file with the .ser extension, and you can restore and reconstruct the state of the Java object through this file, a reverse process called deserialization.

What is Java serialization

Serialization is the process of changing the object to a binary format that can be saved to disk or sent to other running Java virtual machines over the network, and the object state can be recovered by deserialization. Java serialization API provides a standard mechanism for developers to handle object serialization through java.io.Serializable and java.io.Externalizable interfaces, ObjectInputStream and ObjectOutputStream. Java programmers are free to choose standard serialization based on the class structure or their custom binary format, which is generally considered to be the best practice, because the serialized binary format becomes part of the class output API and may break the encapsulation of private and package-visible attributes in Java.

How to serialize

It's easy to serialize classes in Java. Your Java class only needs to implement the java.io.Serializable interface, and JVM will serialize the Object object in the default format. The need to make a class serializable intentionally. Class sequencability may be a long-term cost, which may limit you to modify or change its implementation. When you change the structure of a class by implementing add interfaces, adding or removing any fields may break the default serialization, which minimizes the possibility of incompatibility by customizing the binary format, but it still takes a lot of effort to ensure backward compatibility. An example of how serialization limits your ability to change classes is SerialVersionUID. If SerialVersionUID is not explicitly declared, JVM generates its structure based on the class structure, which depends on the class implementation interface and several other factors that may change. Suppose your new version of the class file implements another interface, JVM will generate a different SerialVersionUID, and when you try to load old objects serialized by the old version of the program, you will get an invalid class exception InvalidClassException.

Question 1) what is the difference between serializable interfaces and externally available interfaces in Java?

This is the most frequently asked question in Java serialization interviews. Here's my version of Externalizable, which gives us the writeExternal () and readExternal () methods, which gives us the flexibility to control the Java serialization mechanism instead of relying on Java's default serialization. The correct implementation of the Externalizable interface can significantly improve the performance of applications.

Question 2) how many serializable methods are there? If there are no methods, what is the purpose of serializable interfaces?

The serializable Serializalbe interface exists in the java.io package and forms the core of Java serialization mechanism. It has no method and is also called a tagged interface in Java. When a class implements the java.io.Serializable interface, it becomes serializable in Java and instructs the compiler to serialize the object using the Java serialization mechanism.

Question 3) what is serialVersionUID? What happens if you don't define this?

One of my favorite interview questions about Java serialization. SerialVersionUID is a private static final long ID. When it is printed on an object, it is usually the hash code of the object. You can use the JDK tool serialver to view the serialVersionUID of the serialized object. SerialVerionUID is used for versioning of objects. You can also specify serialVersionUID in the class file. The consequence of not specifying serialVersionUID is that when you add or modify any fields in a class, the serialized class will not be able to recover because the serialVersionUID generated for the new class and the old serialized object will be different. The Java serialization process relies on the correct serialization object to recover the state, and throws an java.io.InvalidClassException invalid class exception if the serialization object sequence version does not match. For more information about serialVersionUID, see this article, which requires FQ.

Q4) when serializing, do you want some members not to serialize? How do you achieve it?

Another frequently asked serialized interview question. This is also sometimes asked, such as what are transient trasient variables, transient and static variables will be serialized, so if you do not want any field to be part of the state of the object, then declare it static or transient according to your needs, so that it will not be included in the Java serialization process.

Question 5) what happens if a member of the class does not implement a serializable interface?

A simple question about the Java serialization process. If you try to serialize an object that implements a serializable class, but the object contains a reference to a non-serializable class, a non-serializable exception NotSerializableException is thrown at run time, which is why I always put a serializable alert (in my code comments section), one of the code comments best practices, instructing developers to remember this fact and be careful when adding new fields to the serializable class.

Question 6) if the class is serializable but its superclass is not, what is the state of the instance variable inherited from the superclass after deserialization?

The Java serialization process continues only when the object hierarchy is serializable, that is, implementing the serializable interface in Java, and the value of the instance variable inherited from the superclass is initialized by calling the constructor, a superclass that is not serializable during deserialization. Once the constructor link is started, it is impossible to stop, so the constructor is executed even if the higher classes in the hierarchy implement a serializable interface. As you can see from the presentation, this serialized interview question looks tricky and difficult, but if you are familiar with key concepts, it is not difficult.

Question 7) can you customize the serialization process, or can you override the default serialization process in Java?

The answer is yes, you can. We all know that you need to call ObjectOutputStream.writeObject (saveThisObject) to serialize an object and read the object with ObjectInputStream.readObject (), but the Java virtual machine provides you with one more thing, which is to define these two methods. If you define these two methods in a class, JVM will call both methods instead of applying the default serialization mechanism. Here you can customize the behavior of object serialization and deserialization by performing any type of preprocessing or post-processing tasks. It is important to note that these methods are declared private to avoid being inherited, overridden, or overloaded. Since only the Java virtual machine can call private methods of your class, the integrity of your class will be preserved and Java serialization will work properly. In my opinion, this is one of the best questions you can ask in any Java serialization interview, and a good follow-up question is, why provide a custom serialization form for your object?

Question 8) assuming that the superclass of the new class implements a serializable interface, how to prevent the new class from being serialized?

A thorny interview question in Java serialization. If the class's Super class already implements a serializable interface in Java, it can already be serialized in Java, because you can't cancel the interface, it can't really make it unserialized, but there is a way to avoid new class serialization. To avoid Java serialization, you need to implement the writeObject () and readObject () methods in the class, and you need to throw an unserialized exception NotSerializableException from that method. This is another benefit of customizing the Java serialization process, as described in the serialized interview question above, and is usually raised as a follow-up question as the interview progresses.

Question 9) what methods are used in serialization and deserialization in Java?

This is a common interview question, and basically in serialization, the interviewer tries to know if you are familiar with the use of readObject (), writeObject (), readExternal (), and writeExternal (). Java serialization is done by the java.io.ObjectOutputStream class. This class is a filter stream that is encapsulated in a lower-level byte stream to handle the serialization mechanism. To store any object through the serialization mechanism, we call ObjectOutputStream.writeObject (savethisobject) and deserialize the object, which we call the ObjectInputStream.readObject () method. The writeObject () method is called to trigger the serialization process in the java. One important thing to note about the readObject () method is that it is used to read bytes from persistence, create objects from those bytes, and return an object that requires the type to be cast to the correct type.

Question 10) suppose you have a class that serializes and stores it in persistence, and then modifies the class to add new fields. What happens if you deserialize a serialized object?

This depends on whether the class has its own serialVersionUID. As we know from the above problem, if we do not provide serialVersionUID, the Java compiler will generate it, which is usually equal to the hash code of the object. By adding any new fields, it is possible that the new serialVersionUID generated for the new version of the class is different from the serialized object, in which case the Java serialization API throws a java.io.InvalidClassException, so it is recommended that you have your own serialVersionUID in your code and ensure that it remains the same in a single class.

11) what are compatible and incompatible changes in the Java serialization mechanism?

The real challenge is to change the class structure by adding any fields, methods, or deleting any fields or methods, by using serialized objects. According to the Java serialization specification, adding any field or method faces compatible changes and changes to the class hierarchy or de-serializable interfaces implemented, some of which are subject to incompatible changes. For a complete list of compatible and incompatible changes, I recommend reading the Java serialization specification.

12) can we transmit a serialized object over the network?

Yes, you can transfer serialized objects over the network, because Java serialized objects are still kept in bytes, and bytes can be sent over the network. You can also store serialized objects on disk or in a database as Blob.

13) which variables are not serialized during Java serialization?

This question is asked differently, but for the same purpose, whether Java developers know the details of static and transient variables. Because static variables belong to classes, not objects, they are not part of the object state, so they are not saved during Java serialization. Because Java serialization retains only the state of the object, not the object itself. Transient variables are also not included in the Java serialization process and are not part of the serialized state of the object. After asking this question, the interviewer will ask the follow-up, if you don't store the values of these variables, what is the value of these variables once you deserialize these objects and recreate them? This is what you have to consider.

9. Why does the wait method in Java need to be called in the method of synchronized?

Another thorny core Java issue, wait and notify. They are called in a method or synchronized block marked with synchronized, because wait and modify need to monitor the Object on which wait or notify-get is called.

Most Java developers know that the wait (), notify (), and notifyAll () methods of an object class must be called in a synchronized method or synchronized block in Java, but how many times have we thought about why wait, notify, and notifyAll in Java come from synchronized blocks or methods?

This question was recently asked by a friend of mine in a Java interview. He thought about it and replied: if we don't call the wait () or notify () method from the synchronization context, we will receive the IllegalMonitorStateException in Java.

His answer was correct from the actual effect last year, but the interviewer will not be completely satisfied with the answer and hopes to explain the question to him. He and I discussed the same question after the interview, and I think he should tell the interviewer about the race conditions between wait () and notify () in Java, which may exist if we don't call them in synchronous methods or blocks.

Let's see how race conditions occur in Java programs. It is also one of the popular thread interview questions and often appears in phone and face-to-face interviews with Java developers. So, if you are preparing for a Java interview, then you should prepare such questions, and a book that can really help you is the Java programmer interview Formula Book. This is a rare book that covers almost all the important topics of Java interviews, such as core Java, multithreading, IO and NIO, and frameworks such as Spring and Hibernate. You can check it here.

Why wait for a wait method from a synchronized method in Java? why must it be called from a synchronized block or method in Java? We mainly use wait (), notify (), or notifyAll () methods for inter-thread communication in Java. A thread is waiting after checking the condition, for example, in the classic producer-consumer problem, if the buffer is full, the producer thread waits, and the consumer thread notifies the producer thread after using the element to create space in the buffer. Call the notify () or notifyAll () method to notify one or more threads that a condition has changed, and once the thread is notified to leave the synchronized block, all waiting threads begin to acquire the waiting object lock, and the lucky thread returns from the wait () method after re-acquiring the lock and continues.

Let's break the whole operation into several steps to see the possibility of a race condition between the wait () and notify () methods in Java, and we will use the Produce Consumer thread example to better understand the scenario:

The Producer thread tests the condition (whether the buffer is complete) and confirms that it must wait (find that the buffer is full).

The Consumer thread sets the condition after using the elements in the buffer.

The Consumer thread calls the notify () method; this will not be heard because the Producer thread has not yet waited.

The Producer thread calls the wait () method and enters the waiting state.

Therefore, due to race conditions, we may lose notifications, and if we use a buffer or only one element, the production thread will wait forever and your program will hang. " Waiting for notify and notifyall in java synchronization now let's consider how to solve this potential race condition? This race condition is resolved by using the synchronized keyword and locking provided by Java. In order to call wait (), notify (), or notifyAll (), in Java, we must acquire a lock on the object on which we call the method. Because the wait () method in Java releases the lock before waiting and reacquires the lock method before returning from wait (), we must use this lock to ensure that the check condition (whether the buffer is full) and the setting condition (getting the element from the buffer) are atomic, which can be achieved by using the synchronized method or block in Java.

I'm not sure if this is what the interviewer actually expected, but I think this at least makes sense, please correct me if I am wrong, please tell us if there is any other compelling reason to call the wait (), notify () or notifyAll () method in Java.

To sum up, we use the synchronized method in Java or the synchronized block to call the wait (), notify (), or notifyAll () method in Java to avoid:

1) Java throws IllegalMonitorStateException if we don't call the wait (), notify () or notifyAll () methods from the synchronization context.

2) any potential competition conditions between wait and notify methods in Javac.

10. Can you override static methods with Java? What if I create the same method in a subclass is a compile-time error?

No, you can't override static methods in Java, but declaring an identical method in a subclass is not a compile-time error, which is called a method hidden in Java.

You cannot override static methods in Java because methods override runtime-based dynamic binding, and static methods are bound with static bindings at compile time. Although you can declare a method with the same name and method signature in a subclass, it looks like you can override a static method in Java, but this is actually method hiding. Java does not parse the method call at run time, and the method is called depending on the Object type used to invoke the static method. This means that if you use the type of the parent class to call the static method, then the original static will be called from the parent class, on the other hand, if you use the type of the subclass to call the static method, the method from the subclass will be called. In short, you cannot override static methods in Java. If you use Java IDE like Eclipse or Netbeans, they will warn that static methods should be called with class names instead of objects, because static methods cannot be overridden in Java.

/ * Java program which demonstrate that we can not override static method in Java. * Had Static method can be overridden, with Super class type and sub class object * static method from sub class would be called in our example, which is not the case. * / public class CanWeOverrideStaticMethod {public static void main (String args []) {Screen scrn = new ColorScreen (); / / if we can override static, this should call method from Child class scrn.show () / / IDE will show warning, static method should be called from classname}} class Screen {/ * * public static method which can not be overridden in Java * / public static void show () {System.out.printf ("Static method from parent class") }} class ColorScreen extends Screen {/ * static method of same name and method signature as existed in super * class, this is not method overriding instead this is called * method hiding in Java * / public static void show () {System.err.println ("Overridden static method in Child Class in Java");}}

Output:

Static method from parent class

This output confirms that you cannot override static methods in Java and that static methods are bound based on type information rather than based on Object. If you want to override a static mehtod, a method in the subclass or ColorScreen is called. All of this is under discussion. We can override static methods in Java. We have confirmed that no, we cannot override static methods, we can only hide static methods in Java. Creating a static method with the same name and mehtod signature is called a Java hidden method. IDE will display a warning: "static methods should be called with a class name instead of an object," because static methods cannot be overridden in Java.

This is the end of the content of "what are the 10 difficult Java interview questions"? thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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