Java face questions and Answers-(top) _java

Source: Internet
Author: User
Tags arrays comparable data structures exception handling garbage collection inheritance serialization thread class

In this article we will discuss various types of face questions in a Java interview that will allow employers to test the candidate's Java and common object-oriented programming capabilities. The following chapters are divided into two, the first one will discuss object-oriented programming and its features, about Java and its features common problems, Java collection class, garbage collector, the second main discussion of exception handling, Java applet, SWING,JDBC, remote method call (RMI), Servlet and JSP.

Begin!

Directory

Object-oriented programming (OOP)

Common Java Problems

Java Threads

Java Collection Class

Garbage collector

Object-oriented programming (OOP)

Java is a computer programming language that supports concurrency, class, and object-oriented. The benefits of object-oriented software development are listed below:

    1. Code development is modular and easier to maintain and modify.
    2. Code reuse.
    3. Enhance the reliability and flexibility of your code.
    4. Increase the comprehensible nature of the code.

Object-oriented programming has many important features, such as encapsulation, inheritance, polymorphism, and abstraction. In the following sections we will analyze these features one by one.

Packaging

Encapsulation provides an object with the ability to hide internal attributes and behavior. Object provides methods that can be accessed by other objects to change its internal data. In Java, there are 3 modifiers: public,private and protected. Each modifier gives different access rights to the other objects located in the same package or under different packages.

Some of the benefits of using encapsulation are listed below:

    1. Protects the state within an object by hiding its properties.
    2. Increases the availability and maintainability of your code, because the behavior of an object can be changed individually or by extension.
    3. Prevents undesirable interaction between objects to improve modularity.

Refer to this document for more details and examples of encapsulation.

Polymorphic

Polymorphism is the ability of a programming language to display the same interface for different underlying data types. An operation on a polymorphic type can be applied to other types of values.

Inherited

Inheritance provides an object with the ability to get fields and methods from the base class. Inheritance provides a reusable line of code, or you can add new attributes to an existing class without modifying the class.

Abstract

Abstraction is the process of separating ideas from specific instances, so you create classes based on their capabilities rather than implementation details. Java supports the creation of an abstract class that has only a leaky interface and does not contain a method implementation. The main purpose of this abstract technique is to separate the behavior of the class from the implementation details.

Different points of abstraction and encapsulation

Abstraction and encapsulation are complementary concepts. On the one hand, abstract attention to the behavior of the object. On the other hand, encapsulates the details of the object's behavior. Encapsulation is generally done by hiding the internal state information of the object, so the package can be viewed as a strategy for providing abstraction.

Common Java Problems

1. What is a Java virtual machine? Why is Java called a "platform-independent programming language"?

A Java Virtual machine is a virtual machine process that can perform Java bytecode. Java source files are compiled into bytecode files that can be executed by the Java virtual machine.

Java is designed to allow applications to run on any platform without requiring programmers to rewrite or recompile individually for each platform. The Java Virtual machine makes this possible because it knows the instruction length and other features of the underlying hardware platform.

What is the difference between 2.JDK and JRE?

The Java Runtime Environment (JRE) is the Java virtual machine that will execute the Java program. It also contains the browser Plug-ins needed to execute the applet. The Java Development Kit (JDK) is a complete Java software development package that contains JRE, compilers, and other tools (such as the Javadoc,java debugger) that allow developers to develop, compile, and execute Java applications.

3. What does the "static" keyword mean? Can you override (override) a private or static method in Java?

The "static" keyword indicates that a member variable or a member method can be accessed without an instance variable of the class to which it belongs.
The static method in Java cannot be overridden because method overrides are dynamically bound based on Run-time, and the static method is statically bound at compile time. The static method is not relevant to any instance of the class, so it is not conceptually applicable.

4. Can I access a non-static variable in a static environment?

A static variable is a class in Java and has the same value in all instances. The static variable is initialized when the class is entered by Java Virtual aircraft. If your code tries to access a non static variable without an instance, the compiler will complain because the variables have not yet been created and are not associated with any instances.

What data types are supported by 5.Java? What is automatic unboxing?

The basic data types in the Java language Support 8 are:

    1. Byte
    2. Short
    3. Int
    4. Long
    5. Float
    6. Double
    7. Boolean
    8. Char

Automatic boxing is a transformation of the Java compiler between the base data type and the corresponding object wrapper type. For example: Convert int into integer,double into double, and so on. The opposite is automatic unpacking.

What does the method override (overriding) and method overload (overloading) in 6.Java mean?

Method overloads in Java occur in the same class with two or more methods with the same method name but with different parameters. In contrast, method overrides are a way of saying that subclasses redefine the parent class. Method overrides must have the same method name, parameter list, and return type. The overridden person may not restrict access to the methods it overrides.

7.Java, what is a constructor? What is a constructor overload? What is a copy constructor?

When a new object is created, the constructor is invoked. Each class has a constructor. The Java compiler creates a default constructor for this class when the programmer does not provide a constructor for the class.

Constructor overloads and method overloads in Java are very similar. You can create multiple constructors for a class. Each constructor must have its own unique argument list.

Java does not support copy constructors like C + +, which is different because Java does not create a default copy constructor if you do not write the constructor yourself.

8.Java Do you support multiple inheritance?

Not supported, Java does not support multiple inheritance. Each class can inherit only one class, but can implement multiple interfaces.

9. What is the difference between an interface and an abstract class?

Java provides and supports the creation of abstract classes and interfaces. Their implementation has something in common, and the difference is:

    1. All methods in an interface are implicitly abstract. Abstract classes, in turn, can contain both abstract and non-abstract methods.
    2. A class can implement many interfaces, but can inherit only one abstract class
    3. Class if you want to implement an interface, it must implement all the methods that the interface declares. However, a class may not implement all the methods declared by an abstract class, and of course, in this case, the class must also be declared abstract.
    4. An abstract class can implement an interface without providing an interface method implementation.
    5. The variables declared in the Java interface are final by default. An abstract class can contain non final variables.
    6. The member functions in the Java interface are public by default. The member functions of an abstract class can be private,protected or public.
    7. Interfaces are absolutely abstract and cannot be instantiated. An abstract class can also not be instantiated, but it can be invoked if it contains the main method.

You can also refer to the difference between an abstract class and an interface in JDK8

10. What is value passing and reference passing?

object is passed by value, meaning that a copy of the object is passed. Therefore, even changing the copy of the object does not affect the value of the source object.

The object is passed by reference, which means that it is not a real object, but a reference to the object. As a result, the external changes to the referenced object are reflected on all objects.

Java Threads

11. What is the difference between process and thread?

A process is an executing application, and a thread is a sequence of execution within a process. A process can have more than one thread. Threads are also called lightweight processes.

12. There are several different ways to create threads? Which one do you like? Why?

There are three ways to create threads:

    1. Inherit Thread class
    2. Implement Runnable interface
    3. Applications can use the executor framework to create thread pools

Implementing the Runnable interface is a more popular approach because it does not need to inherit the thread class. In the case where other objects have been inherited in the application design, this requires multiple inheritance (and Java does not support multiple inheritance) and can only implement interfaces. At the same time, the thread pool is very efficient and easy to implement and use.

13. A general explanation of the several available states of the thread.

During execution, the thread can be in the following states:

    1. Ready (Runnable): Threads are ready to run, not necessarily immediately.
    2. In-run (Running): The process is executing the thread's code.
    3. In Wait (waiting): The thread is in a blocked state, waiting for the external processing to end.
    4. Sleep (sleeping): Thread is forced to sleep.
    5. I/O blocking (Blocked on I/O): Waiting for I/O operation to complete.
    6. Synchronous blocking (Blocked on synchronization): Waiting to acquire lock.
    7. Death (Dead): Thread completes execution.

14. What is the difference between a sync method and a synchronized code block?

In the Java language, each object has a lock. Threads can use the Synchronized keyword to get a lock on an object. The Synchronized keyword can be applied at the method level (coarse-grained locks) or at the code block level (fine-grained locks).

15. What is the thread synchronization inside the monitor? What level of synchronization should the program take?

Monitors and locks are used together in a Java virtual machine. Monitor monitors a synchronized block of code, ensuring that only one thread executes the synchronized code block at a time. Each monitor is associated with an object reference. The thread does not allow synchronization code to execute until the lock is acquired.

16. What is a deadlock (deadlock)?

A deadlock occurs when two processes are waiting for each other to execute before continuing. The result is that two processes are trapped in infinite waiting.

17. How to ensure that n threads can access n resources without causing deadlocks?

When using multithreading, a very simple way to avoid deadlocks is to specify the order in which locks are acquired and to force threads to acquire locks in the order specified. Therefore, if all threads lock and release locks in the same order, there is no deadlock.

Java Collection Class

What are the basic interfaces of the 18.Java collection class framework?

The Java Collection class provides a well-designed set of interfaces and classes that support manipulating a set of objects. The most basic interfaces within the Java Collection class are:

    1. Collection: Represents a set of objects, each of which is its child element.
    2. Set: Collection that does not contain duplicate elements.
    3. List: Sequential collection, and can contain duplicate elements.
    4. Map: Keys can be mapped to values (value) of the object, the key can not be repeated.

19. Why does the collection class not implement the cloneable and serializable interfaces?

The collection class interface specifies a set of objects called elements. Each specific implementation class of a collection class interface can choose to save and sort elements in its own way. Some collection classes allow duplicate keys, some of which are not allowed.

20. What is an iterator (iterator)?

The iterator interface provides many ways to iterate over the elements of a collection. Each collection class contains an instance of an iterator that can return instances of the
Iterative methods. Iterators can delete elements of the underlying collection during the iteration.

The semantics and meaning of cloning (cloning) or serialization (serialization) are related to specific implementations. Therefore, it is up to the concrete implementation of the collection class to decide how to be cloned or serialized.

What is the difference between 21.Iterator and listiterator?

Here is a list of their differences:

    1. Iterator can be used to traverse the set and list collection, but Listiterator can only traverse the list.
    2. Iterator to the set can only be forward traversal, listiterator can be both forward and backwards.
    3. Listiterator implements the iterator interface and includes other functions, such as adding elements, replacing elements, getting the index of the previous and last elements, and so on.

22. What is the difference between rapid failure (fail-fast) and security failure (fail-safe)?

Iterator security failure is based on a copy of the underlying collection, so it is not affected by modifications on the source collection. All of the collection classes below the Java.util package are fast failures, and all the classes underneath the Java.util.concurrent package are security failures. A fast-fail iterator throws a Concurrentmodificationexception exception, and a security-failed iterator never throws such an exception.

What is the working principle of the hashmap in 23.Java?

HashMap in Java store elements in the form of key-value pairs (key-value). HashMap requires a hash function that uses the hashcode () and Equals () methods to add and retrieve elements to the collection/from the collection. When the put () method is invoked, HashMap calculates the hash value of the key and then stores the key value pairs on the appropriate index in the collection. If the key already exists, value is updated to the new value. Some of the key features of HashMap are its capacity (capacity), load factor (loading factor), and expansion limit (threshold resizing).

Where is the importance of the 24.hashCode () and Equals () methods?

HashMap in Java Use the hashcode () and Equals () methods to determine the index of key-value pairs, which are also used when the value is obtained from the key. If the two methods are not implemented correctly, two different keys may have the same hash value, and therefore may be considered equal by the collection. Also, these two methods are used to discover duplicate elements. So the realization of these two methods is very important to the accuracy and correctness of hashmap.

What's the difference between 25.HashMap and Hashtable?

    1. HashMap and Hashtable both implement the map interface, so many features are very similar. However, they have the following different points:
    2. HashMap allows keys and values to be null, while Hashtable does not allow keys or values to be null.
    3. Hashtable is synchronized, and HashMap is not. Therefore, HashMap is more suitable for single-threaded environments, while Hashtable is suitable for multi-threaded environments.
    4. HashMap provides a collection of keys that are available for application iterations, so HashMap is fast failing. On the other hand, Hashtable provides an enumeration of keys (enumeration).
    5. Hashtable is generally considered to be a legacy class.

26. What is the difference between an array and a list (ArrayList)? When should I use array instead of ArrayList?

The different points of array and ArrayList are listed below:

    1. An array can contain basic types and object types, and ArrayList can only contain object types.
    2. The array size is fixed, and the size of the ArrayList is dynamically variable.
    3. ArrayList offers more methods and features, such as: AddAll (), RemoveAll (), iterator (), and so on.
    4. For basic type data, the collection uses automatic boxing to reduce the coding effort. However, this approach is relatively slow when dealing with a fixed sized base data type.

What's the difference between 27.ArrayList and LinkedList?

Both ArrayList and LinkedList have implemented the list interface, and they have the following different points:

ArrayList is an indexed data interface, with an array at the bottom. It can randomly access elements in O (1) time complexity. In this case, LinkedList stores its data in the form of a list of elements, each of which is linked to its previous and subsequent elements, in which cases the time complexity of finding an element is O (n).

Add and delete operations are faster than arraylist,linkedlist inserts, because when an element is added to any location in the collection, you do not need to recalculate the size or update the index as an array.

LinkedList is more memory than ArrayList because LinkedList stores two references for each node, one pointing to the previous element and one to the next.

You can also refer to ArrayList vs. LinkedList.

What is the 28.Comparable and comparator interface? List the differences between them.

Java provides a comparable interface that contains only one CompareTo () method. This method can be sorted for two objects. Specifically, it returns a negative number, 0, and a positive number to indicate that the input object is less than, equal to, greater than the existing object.

Java provides comparator interfaces that contain compare () and Equals () two methods. The Compare () method is used to sort two input parameters, return a negative number, 0, and a positive number indicates that the first argument is less than, equal to, and greater than the second argument. The Equals () method requires an object as a parameter that determines whether the input parameter is equal to the comparator. This method returns true only if the input parameter is also a comparator and the input parameter is the same as the current comparator sort result.

29. What is a Java Priority queue (Priority queue)?

Priorityqueue is an unbounded queue based on a priority heap whose elements are sorted in natural order (natural orders). At the time of creation, we can give it a comparer that is responsible for sorting the elements. Priorityqueue do not allow null values because they do not have a natural order, or they do not have any associated comparators. Finally, Priorityqueue is not thread-safe, and the time complexity of team and Out is O (log (n)).

30. Do you know the big O sign (big-o notation)? Can you give examples of different data structures?

The Big O notation describes the size of the algorithm, or how good it is in the worst-case scenario, when the elements inside the data structure increase.
The Big O symbol can also be used to describe other behaviors, such as memory consumption. Because the collection class is actually a data structure, we typically use the Big O notation to choose the best implementation based on time, memory, and performance. Large o notation can give a good description of the performance of a large number of data.

31. How do you weigh the use of unordered arrays or ordered arrays?

The best thing about an ordered array is that the time complexity of the lookup is O (log n), and the unordered array is O (n). The disadvantage of an ordered array is that the time complexity of the insert operation is O (n), because the value of the element needs to be moved back to place the new element. Instead, the insertion time complexity of unordered arrays is constant O (1).

What are the best practices for the 32.Java collection class framework?

Choosing the type of collection you want to use correctly depends on the performance of your application, such as: if the size of the element is fixed and you know beforehand, we should use an array instead of a ArrayList.
Some collection classes allow the initial capacity to be specified. Therefore, if we can estimate the number of stored elements, we can set the initial capacity to avoid recalculation of hash values or expansion.

For type safety, the reason for readability and robustness is always to use generics. At the same time, using generics can also avoid run-time classcastexception.
Using the invariant Class (immutable Class) provided by JDK as a key to the map avoids hashcode () and Equals () methods for our own classes.
Interfaces are better than implementations when programming.
If the underlying collection is actually empty, return a set of 0 or an array, and do not return NULL.

What are the differences between 33.Enumeration interface and iterator interface?

The enumeration speed is twice times the iterator and consumes less memory. However, iterator is far more secure than enumeration because other threads cannot modify objects in the collection that is being traversed by the iterator. At the same time, iterator allows the caller to delete elements from the underlying collection, which is impossible for enumeration.

What's the difference between 34.HashSet and TreeSet?

HashSet is implemented by a hash table, so its elements are unordered. Add (), remove (), the time complexity of the contains () method is O (1).

TreeSet, on the other hand, is implemented by a tree-shaped structure in which elements are ordered. Therefore, add (), remove (), the time complexity of the contains () method is O (Logn).

Garbage collector (Garbage collectors)

What is the purpose of garbage collection in 35.Java? When is garbage collected?

The purpose of garbage collection is to identify and discard objects that are no longer used to release and reuse resources.

What will 36.system.gc () and RUNTIME.GC () do?

These two methods are used to prompt the JVM for garbage collection. However, it depends on the JVM to start or defer garbage collection immediately.

When is the 37.finalize () method invoked? What is the purpose of the destructor (finalization)?

The garbage collector invokes the object's Finalize () method before releasing the memory occupied by the object. It is generally recommended that the resources held by objects be freed in this method.

38. If the object's reference is set to NULL, will the garbage collector immediately release the memory occupied by the object?

No, in the next garbage collection cycle, this object will be recyclable.

What is the structure of the 39.Java heap? What is the permanent generation in the heap (Perm Gen space)?

The JVM's heap is the Run-time data area, and both instances and arrays of all classes allocate memory on the heap. It is created when the JVM is started. The heap memory that an object occupies is reclaimed by an automatic memory management system, or garbage collector.

Heap memory is made up of surviving and dead objects. The surviving object is that the application can be accessed and will not be garbage collected. The object of death is an object that is not accessible to the application and has not been reclaimed by the garbage collector. Until the garbage collector reclaims these objects, they will always occupy the heap of memory space.

40. What is the difference between a serial (serial) collector and a throughput (throughput) collector?

The throughput collector uses a parallel version of the new generation garbage collector, which is used for medium-scale and large-scale data applications. The serial collector is sufficient for most small applications (about 100M of memory on a modern processor).

41. In Java, when can objects be garbage collected?

When an object becomes inaccessible to an application that is currently using the object, the object can be recycled.

Will garbage collection occur in the 42.JVM's permanent generation?

Garbage collection does not occur in the permanent generation, and if the permanent generation is full or the threshold is exceeded, a complete garbage collection (full GC) is triggered. If you look closely at the output of the garbage collector, you will find that the permanent generation is also reclaimed. This is why the correct permanent generation size is important for avoiding full GC. Please refer to the following Java8: from permanent generation to metadata area

(Translator Note: The JAVA8 has been removed from the permanent generation, and a new native memory area called the metadata area) has been added.

The above is the Java interview problem of data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

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.