Most useful Java face questions

Source: Internet
Author: User
Tags finally block modifier switch case

1. What are thread local variables? Answer

A thread local variable is a variable that is confined to the thread itself and is owned by the thread itself and is not shared among multiple threads. Java provides the ThreadLocal class to support thread-local variables, which is a way to implement thread safety. However, when using thread-local variables in a managed environment (such as a Web server), you should be particularly careful, in which case the worker thread has a longer life cycle than any application variable. Once any thread local variable is not released after the work is completed, there is a risk of a memory leak in the Java application.

2. Write a piece of code with wait-notify to solve the producer-consumer problem? Answer

Please refer to the sample code in the answer. Just remember to call the Wait () and notify () methods in the synchronization block, and if blocked, test the wait condition by looping.

3. Write a thread-safe singleton mode (Singleton) in Java? Answer

Please refer to the sample code in the answer, which is a step-by-step guide to creating a thread-safe Java Singleton class. When we say thread safety, it means that even if initialization is in a multithreaded environment, a single instance can still be guaranteed. In Java, using enumerations as singleton classes is the simplest way to create a thread-safe singleton pattern.

What is the difference between the sleep method and the Wait method in 4.Java? Answer

While both are used to pause the currently running thread, sleep () is actually just a short pause because it does not release the lock, and wait () means that the condition waits, which is why the method is releasing the lock because the other waiting thread can get to the lock when the condition is met.

5. What are immutable objects (immutable object)? How do I create an immutable object in Java? Answer

Immutable objects means that once an object is created, the state can no longer be changed. Any modifications will create a new object, such as String, Integer, and other wrapper classes. For details, see the answer and step-by-step instructions to create an immutable class in Java.

6. Can we create an immutable object that contains Mutable objects?

Yes, we can create an immutable object that contains Mutable objects, you just have to be careful not to share references to mutable objects, and if you need to change, return a copy of the original object. The most common example is a reference to an object that contains a Date object.

Data types and Java Basics interview questions

What data types should be used to represent prices in 7.Java? Answer

If you are not particularly concerned about memory and performance, use BigDecimal, otherwise use a double type of predefined precision.

8. How do I convert a byte to a String? Answer

You can use the constructor of the String to receive the byte[] parameter to convert, the point to be aware of is the correct encoding to use, otherwise the platform default encoding, which may be the same as the original encoding, or may be different.

How do I convert bytes to a long type in 9.Java?

You answer the question,:-).

10. Can we cast int to a variable of type byte? What happens if the value is greater than the range of type byte?

Yes, we can do the cast, but the int in Java is 32 bits, and byte is 8 bits, so if coercion is, the high 24 bits of the int type will be discarded, and the range of byte type is from-128 to 128.

11. There are two classes, B inherits A,c inherit B, can we convert B to C? such as C = (c) B; (Answer answer)

12. Which class contains the Clone method? Is it a cloneable or an Object? Answer

Java.lang.Cloneable is an indicative interface that does not contain any methods, and the Clone method is defined in the object class. And you need to know that the Clone () method is a local method, which means that it is implemented by C or C + + or other native languages.

is the 13.Java + + operator thread-safe? Answer

is not a thread-safe operation. It involves multiple instructions, such as reading the value of a variable, increasing it, and then storing it back into memory, and this process may occur when multiple threads are involved.

14.a = difference between A + B and a + = B (Answer)

+ = implicitly casts the result type of the plus operation to the type holding the result. If two of these integers are added, such as Byte, short, or int, they are first promoted to the int type, and then the addition operation is performed. If the result of the addition operation is greater than the maximum value of a, then A+b will have a compile error, but A + = B is no problem, as follows:

byte a = 127;

byte B = 127;

b = A + B; Error:cannot convert from int to byte

B + = A; Ok

(Translator Note: This place should be expressed in error, in fact, regardless of the value of A+b, the compiler will error, because the a+b operation will promote A, b to the int type, so the int type assigned to byte will compile an error)

15. Can I assign a double value to a variable of type long without casting? Answer

No, you can't. You cannot assign a double value to a variable of type long without forcing a type conversion, because the range of double types is wider than the long type, so you must cast.

16.3*0.1 = = 0.3 What will be returned? True or False? Answer

False, because some floating-point numbers are not exactly represented.

Which of the 17.int and integers consumes more memory? Answer

An Integer object consumes more memory. An Integer is an object that needs to store the object's metadata. But int is a primitive type of data, so it takes up less space.

18. Why is the String in Java immutable (immutable)? (Answer answer)

The string in Java is immutable because Java designers believe that strings are used very frequently, and that setting the string to immutable allows multiple clients to share the same string. See the answer for more details.

19. Can we use String in Switch? (Answer answer)

Starting with Java 7, we can use strings in the switch case, but this is just a syntactic sugar. The internal implementation uses the hash code of the string in switch.

What is the constructor chain in 20.Java? (Answer answer)

When you call another constructor from a constructor, it is the constructor chain in Java. This situation only occurs when the constructor of the class is overloaded.

Interview questions for the JVM underlying and GC (garbage Collection)

In a 21.64-bit JVM, the length of int is the majority?

In Java, the length of an int type variable is a fixed value, regardless of the platform, and is 32 bits. This means that in 32-bit and 64-bit Java virtual machines, the length of the int type is the same.

What is the difference between 22.Serial and Parallel GC? Answer

Serial and Parallel will cause stop-the-world when the GC executes. The main difference between them is that the serial collector is the default copy collector, there is only one thread when the GC is executed, and the parallel collector uses multiple GC threads to execute.

23. The length of the 32-bit and 64-bit Jvm,int type variables is the majority? Answer

In 32-bit and 64-bit JVMs, the length of the int type variable is the same, both 32-bit or 4-byte.

What is the difference between WeakReference and softreference in 24.Java? Answer

Although both WeakReference and softreference contribute to the efficiency of GC and memory, WeakReference, once the last strong reference is lost, is recycled by GC, and soft references, although not prevented from being recycled, can be deferred to the JVM's low-memory When

How does 25.WeakHashMap work? Answer

Weakhashmap's work is similar to normal HashMap, but using a weak reference as key means that Key/value will be recycled when the key object does not have any references.

What does the 26.JVM option-xx:+usecompressedoops do? Why should I use it? Answer

When you migrate your app from a 32-bit JVM to a 64-bit JVM, the heap memory increases abruptly, almost doubling, as the object's pointer increases from 32 bits to 64 bits. This can also adversely affect the CPU cache (which is much smaller than memory). Because the primary motivation for migrating to a 64-bit JVM is to specify the maximum heap size, you can save some memory by compressing OOP. With the-xx:+usecompressedoops option, the JVM uses 32-bit OOP instead of 64-bit OOP.

27. How do I use the Java program to determine whether the JVM is 32-bit or 64-bit? Answer

You can check some system properties such as Sun.arch.data.model or os.arch to get that information.

What is the maximum heap memory for 28.32-bit JVMS and 64-bit JVMs, respectively? Answer

In theory, the 32-bit JVM heap memory can reach 2^32, or 4GB, but is actually much smaller than this. Different operating systems, such as the Windows system about 1.5 gb,solaris about 3GB. The 64-bit JVM allows you to specify the maximum heap memory, which can theoretically reach 2^64, which is a very large number, and you can actually specify the heap memory size to 100GB. Even some jvms, such as Azul, heap memory to 1000G are possible.

What is the difference between 29.JRE, JDK, JVM, and JIT? Answer

The JRE represents the Java runtime (Java run-time), which is required to run Java references. The JDK represents the Java development tool (Java Development Kit) and is a development tool for Java programs, such as the Java compiler, which also contains the JRE. The JVM represents the Java virtual machine, which is responsible for running Java applications. JIT stands for Instant compilation (Just in Time compilation), and when code executes more than a certain threshold, Java bytecode is converted to native code, such as the main hotspot code being switched to native code, which can greatly improve the performance of Java applications.

30. Explain Java heap space and GC? Answer

When the Java process is started through a Java command, it allocates memory for it. Part of the memory is used to create the heap space, and the memory is allocated from the space when the object is created in the program. A GC is a process inside the JVM that reclaims the memory of an invalid object for future allocations.

JVM Bottom level questions and answers

31. Can you guarantee the GC to execute? Answer

No, although you can call System.GC () or RUNTIME.GC (), there is no way to guarantee the execution of the GC.

32. How do I get the memory used by Java programs? Percentage of heap usage?

The memory-related methods in the Java.lang.Runtime class can be used to obtain the remaining memory, the total memory, and the maximum heap memory. With these methods you can also get the percentage of heap usage and the remaining space of heap memory.

The Runtime.freememory () method returns the number of bytes of space remaining, the number of bytes of total memory in the Runtime.totalmemory () method, and Runtime.maxmemory () returns the maximum memory bytes.

What is the difference between heap and stack in 33.Java? Answer

The heap and stack in the JVM belong to different memory regions and are used for different purposes. Stacks are often used to save method frames and local variables, and objects are always allocated on the heap. Stacks are usually smaller than heaps and are not shared across multiple threads, and the heap is shared by all threads of the entire JVM.

Interview questions and answers about memory

Java Basic Concept Surface question

What is the difference between "a==b" and "A.equals (b)"? Answer

If both A and B are objects, a==b is a reference to compare two objects, and only if A and B point to the same object in the heap to return true, whereas A.equals (b) is a logical comparison, it is often necessary to override the method to provide a comparison of logical consistency. For example, the String class overrides the Equals () method, so it can be used for two different objects, but contains the same letters as the comparison.

What's the use of 35.a.hashcode ()? What is the relationship with A.equals (b)? Answer

The Hashcode () method is the hash value of the corresponding object integral type. It is often used for hash-based collection classes such as Hashtable, HashMap, Linkedhashmap, and so on. It is particularly closely related to the Equals () method. According to the Java specification, two objects that use the equal () method to determine equality must have the same hash code.

What are the differences between 36.final, Finalize, and finally? Answer

Final is a modifier that can modify variables, methods, and classes. If the final modifier variable, it means that the value of the variable cannot be changed after initialization. The Finalize method is a method that is called before the object is recycled, giving the object its own last chance of resurrection, but when it is called Finalize is not guaranteed. Finally is a keyword that is used in conjunction with try and catch for exception handling. The finally block is bound to be executed regardless of whether an exception occurred in the try block.

What is the compile-time constant in 37.Java? What's the risk of using it?

The public static immutable final variable is what we call the compile-time constants, and here is the publicly available option. In fact, these variables are replaced at compile time because the compiler knows the values of these variables and knows that these variables cannot be changed at run time. One problem with this approach is that you use a public compile-time constant in an internal or third-party library, but the value is changed by someone else, but your client is still using the old value, and even you have deployed a new jar. To avoid this situation, be sure to recompile your program when you update the dependent JAR file.

Face questions in the Java collection framework

This section also contains data structures, algorithms, and an array of interview questions

The difference between 38.List, Set, Map, and Queue (answer)

List is an ordered set that allows elements to be duplicated. Some of its implementations can provide constant access time based on subscript values, but this is not guaranteed by the List interface. Set is an unordered collection.

What is the difference between the 39.poll () method and the Remove () method?

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

What is the difference between Linkedhashmap and priorityqueue in 40.Java? Answer

Priorityqueue the element that guarantees the highest or lowest priority is always on the head of the queue, but the order in which Linkedhashmap is maintained is the order in which the elements are inserted. There is no guarantee of order when traversing a priorityqueue, but the Linkedhashmap class guarantees that the traversal order is the order in which the elements are inserted.

41.ArrayList is different from LinkedList? Answer

The most obvious difference is that the arrraylist underlying data structure is an array that supports random access, while LinkedList's underlying data structure book list does not support random access. Using the subscript to access an element, the time complexity of the ArrayList is O (1), while the LinkedList is O (n). For more details, see the answer.

42. What are the two ways to achieve the sorting of a collection? Answer

You can use an ordered set, such as TreeSet or TREEMAP, or you can use a sequential collection, such as list, and then sort by collections.sort ().

How to print a group in 43.Java? (Answer answer)

You can use the arrays.tostring () and arrays.deeptostring () methods to print an array. Because the array does not implement the ToString () method, if you pass the array to the SYSTEM.OUT.PRINTLN () method, you will not be able to print the contents of the group, but arrays.tostring () can print each element.

Is LinkedList in 44.Java a one-way list or a doubly linked list? Answer

is a doubly linked list, you can check the source code of the JDK. In Eclipse, you can use the shortcut key CTRL + T to open the class directly in the editor.

What tree is the TreeMap used in 45.Java? Answer

The TREEMAP in Java is implemented using a red-black tree.

What is the difference between Hashtable and HashMap? Answer

These two classes have many different places, some of which are listed below:

A) Hashtable is a class left over from JDK 1, and HashMap is later added.

b) Hashtable is synchronous and slower, but HashMap has no synchronization policy, so it will be faster.

c) Hashtable does not allow an empty key, but HASHMAP allows a null key to appear.

See the answers to more of the differences.

HashSet in 47.Java, how does the interior work? (Answer answer)

The interior of the HashSet is implemented using HashMap. Since the MAP requires key and value, all keys have a default value. Similar to Hashmap,hashset does not allow duplicate keys, only a null key is allowed, meaning that only one null object is allowed in HashSet.

48. Write a piece of code to remove an element while traversing ArrayList? Answer

The key to the problem is whether the interviewer is using the ArrayList remove () or the Iterator remove () method. Here is a sample code that uses the correct way to implement the sample code that removes the element during traversal without the concurrentmodificationexception exception.

49. Can we write a container class by ourselves and then use the For-each loop code?

Yes, you can write a container class of your own. If you want to use the enhanced loops in Java to traverse, you only need to implement the Iterable interface. If you implement the Collection interface, this property is the default.

The default size of 50.ArrayList and HashMap is the majority? Answer

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:

From Arraylist.java JDK 1.7

private static final int default_capacity = 10;

From Hashmap.java JDK 7

static final int default_initial_capacity = 1 << 4; aka 16

Most useful Java face questions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.