Analysis of Java Question Bank and answer

Source: Internet
Author: User
Tags comparable

Analysis of Java Question Bank and answer
1. What are the advantages of Object-Oriented Programming (OOP?

  • Code development is modular and easier to maintain and modify.
  • Code reuse.
  • Enhance code reliability and flexibility.
  • Increase the comprehensibility of the Code.
2. What are the features of object-oriented programming?

Encapsulation, inheritance, polymorphism, abstraction

Encapsulation

Encapsulation provides objects with the ability to hide internal characteristics and behaviors. The object provides some methods that can be accessed by other objects to change its internal data. In Java, there are three modifiers: public, private, and protected. Each modifier grants different access permissions to other objects in the same package or under different packages.

The advantages of encapsulation are listed below:

  • You can hide the attributes of an object to protect the internal state of the object.
  • This improves code availability and maintainability, because the behavior of objects can be changed or extended independently.
  • Disable poor interaction between objects to improve modularity.
Inheritance

Inheritance provides objects with the ability to obtain fields and methods from the base class. Inheritance provides code reuse. You can also add new features to existing classes without modifying classes.

Polymorphism

Polymorphism is the ability of programming languages to present the same interface to different underlying data types. Operations on one polymorphism type can be applied to values of other types.

Abstraction

Abstract refers to the process of separating ideas from specific instances. Therefore, you need to create classes based on their functions rather than implementation details. Java supports creating abstract classes that only expose interfaces and do not contain method implementations. The main purpose of this abstract technology is to separate the class behavior and implementation details.

3. What is a Java Virtual Machine? Why is Java called a platform-independent programming language "?

Java virtual machine is a virtual machine process that can execute Java bytecode. Java source files are compiled into bytecode files executed by Java virtual machines.

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

4. What is the difference between JDK and JRE?

JRE (Java Runtime Environment) is the Java virtual machine that will execute the Java program. It also contains the browser plug-in required for executing the applet. JDK (Java Development Kit) is a complete Java software development kit, including JRE, compiler and other tools (such as JavaDoc and Java debugger ), developers can develop, compile, and execute Java applications.

5. What does the "static" keyword mean? Can I overwrite a private or static method in Java?

The "static" keyword indicates that a member variable or member method can be accessed without a class instance.

The static method in Java cannot be overwritten, because it is dynamically bound at runtime, while the static method is statically bound at compilation. The static method is irrelevant to any instance of the class, so it is not applicable in concept.

6. can I access non-static variables in a static environment?

Static variables belong to Classes in Java, and their values in all instances are the same. When a class is loaded by a Java virtual machine, static variables are initialized. If your code tries not to use instances to access non-static variables, the compiler reports an error because these variables have not been created and are not associated with any instances.

7. What data types does Java support? What is an Automatic Disassembly box?

Java supports the following basic data types:

  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double
  • Boolean
  • Char

Automatic packing is a conversion between the basic data type and the corresponding object packaging type by the Java compiler. For example, convert int to Integer. Otherwise, it is automatically split.

8. What does Overriding and Overloading in Java mean?

Method overloading in Java occurs when two or more methods in the same class have the same method name but different parameters. The method overwrite means that the subclass redefines the method of the parent class. Method override must have the same method name, parameter list, and return type.

9. In Java, what is a constructor? What is constructor overload? What is a replication constructor?

When a new object is created, the constructor is called. Each class has a constructor. When a programmer does not provide constructors to a class, the Java compiler creates a default constructor for the class.

In Java, constructor Overloading is similar to method overloading. You can create multiple constructors for a class. Each constructor must have its own unique parameter list.

Java does not support replication constructor like C ++. The difference is that if you do not write the constructor yourself, Java will not create the default replication constructor.

10. Does Java support multi-inheritance?

Not Supported. Java does not support multi-inheritance. Each class can inherit only one class, but multiple interfaces can be implemented.

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

Java supports creating abstract classes and interfaces. Their differences are:

  • All methods in the interface are implicitly abstract. Abstract classes can contain both abstract and non-abstract methods.

  • Class can implement many interfaces, but can inherit only one abstract class

  • Class to implement an interface, it must implement all methods declared by the interface. However, classes do not implement all methods declared in abstract classes. In this case, classes must be declared abstract.

  • Abstract classes can implement interfaces without interface methods.

  • The variables declared in the Java interface are final by default. Abstract classes can contain non-final variables.

  • The member functions in the Java interface are public by default. Abstract class member functions can be private, protected, or public.

  • Interfaces are absolutely abstract and cannot be instantiated. Abstract classes cannot be instantiated, but can be called if they contain the main method.

12. What is value transfer? What is reference transfer?

The object is passed by the value, which means that a copy of the object is passed. Therefore, even if the object copy is changed, the value of the source object is not affected.

The object is passed by reference, which means that it is not the actual object but the object reference. Therefore, changes made by the external to the referenced object are reflected on all objects.

13. What are the differences between processes and threads?

A process is an application executed, and a thread is an execution sequence inside the process. A process can have multiple threads. A thread is also called a lightweight process.

14. How can I create a thread? Which one do you like? Why?

There are several ways to create a thread:

  • Inherit Thread class

  • Implement the Runnable interface

  • Applications can use the Executor framework to create thread pools.

The Runnable interface is more popular because it does not need to inherit the Thread class. When other classes have been inherited, this requires multi-inheritance (while Java does not support multi-inheritance) and can only implement interfaces. At the same time, the thread pool is also very efficient and easy to implement and use.

15. Several available states of the thread

The thread can be in the following states:

  • Runnable: The thread is ready to run and cannot be executed immediately.

  • Running: the code of the thread being executed by the process.

  • Waiting: The thread is in the blocking status and waits for external processing to end.

  • Sleeping: The thread is forced to sleep.

  • Blocked on I/O: wait until the I/O operation is completed.

  • Blocked on Synchronization: Wait for the lock to be obtained.

  • Dead: The thread is finished.

16. What is the difference between the synchronization method and the synchronization code block?

In Java, each object has a lock. The thread can use the synchronized keyword to obtain the lock on the object. The synchronized keyword can be applied at the method level (coarse-granularity lock) or code block level (fine-grained lock ).

17. How is thread synchronization performed inside the Monitor? What level of synchronization should the program perform?

The monitor and lock are used together in the Java Virtual Machine. Monitor the synchronization code block to ensure that only one thread executes the synchronization code block at a time. Each monitor is associated with an object reference. The thread cannot execute the synchronization code before obtaining the lock.

18. What is a deadlock )?

A deadlock occurs when both threads are waiting for the execution of the other side to continue. The result is that both threads are in infinite waiting state.

19. How can we ensure that N threads can access N resources without causing deadlocks?

When multithreading is used, a very simple way to avoid deadlock is to specify the order in which the lock is obtained and force the thread to obtain the lock in the specified order. Therefore, if all threads lock and release the lock in the same order, no deadlock will occur.

20. What are the basic interfaces of the Java Collection framework?

The most basic interfaces in the Java Collection class are:

  • Collection: represents a group of objects, each of which is its child element.

  • Set: a Collection that does not contain duplicate elements.

  • List: an ordered Collection that can contain duplicate elements.

  • Map: You can Map a key to a value object. The key cannot be repeated.

21. Why does the collection class not implement the Cloneable and Serializable interfaces?

The semantics and meaning of cloning or serialization are related to the specific implementation. Therefore, the specific implementation of the Collection class should determine how to be cloned or serialized.

22. What is an Iterator )?

The Iterator interface provides many methods to iterate on the collection elements. Each collection class contains an iteration method that can return to an iterator instance. The iterator can delete elements of the underlying set during iteration.

23. What is the difference between Iterator and ListIterator?

Their differences are as follows:

  • Iterator can be used to traverse Set and List sets, but ListIterator can only be used to traverse List.

  • Iterator can only traverse a set in the forward direction. ListIterator can both forward and backward directions.

  • ListIterator implements the Iterator interface and includes other functions, such as adding elements, replacing elements, and obtaining the indexes of the previous and next elements.

24. What is the difference between fail-fast and fail-safe?

The security failure of Iterator is based on copying the underlying set. Therefore, it is not affected by the modification of the source set. All the collection classes under the java. util package fail quickly, while all the classes under the java. util. concurrent package fail safely. The fast-Failed iterator throws a ConcurrentModificationException, and the security-Failed iterator never throws such an exception.

25. What is the working principle of HashMap in Java?

In Java, HashMap stores elements in the form of key-value pairs. HashMap requires a hash function that uses the hashCode () and equals () Methods to add elements to a set and retrieve metadata from the set. When the put () method is called, HashMap calculates the hash value of the key and stores the key-value pairs on the appropriate indexes in the set. If the key already exists, the value is updated to the new value.

26. Where are the importance of hashCode () and equals () Methods reflected?

HashMap in Java uses the hashCode () and equals () methods to determine the index of the key-value pair. These two methods are also used when the value is obtained based on the key. If the two methods are not correctly implemented, the two different keys may have the same hash value, so they may be considered equal by the set. The two methods are also used to find duplicate elements. Therefore, the implementation of these two methods is crucial to the accuracy and correctness of HashMap.

27. What is the difference between HashMap and Hashtable?

Both HashMap and Hashtable implement the Map interface, which has the following differences:

  • HashMap allows keys and values to be null, while Hashtable does not allow keys or values to be null.

  • Hashtable is synchronous, but HashMap is not. Therefore, HashMap is more suitable for single-threaded environments, while Hashtable is more suitable for multi-threaded environments.

  • HashMap provides a set of key that can be supplied with iterations. Therefore, HashMap fails quickly. On the other hand, Hashtable provides Enumeration ).

28. What is the difference between Array and list? When should I use Array instead of ArrayList?

Array and ArrayList have the following differences:

  • Array can contain basic types and object types. ArrayList can only contain object types.

  • The Array size is fixed, and the ArrayList size changes dynamically.

  • ArrayList provides more methods and features, such as addAll (), removeAll (), and iterator.

For basic data types, ArrayList uses automatic packing to reduce the coding workload. However, when processing a basic data type of a fixed size, this method is relatively slow, and Array should be used at this time.

29. What is the difference between ArrayList and rule list?

ArrayList and rule list have the following differences:

  • ArrayList is an index-based data interface, and its underlying layer is an array. It can perform random access to elements with O (1) time complexity. A linked list stores its data in the form of a linked list. Each element is linked with its previous and next elements. In this case, the time complexity of searching for an element is O (n ).

  • Compared with the ArrayList, the insert, add, and delete operations of the sorted list are faster, because when an element is added to any position of the set, you do not need to recalculate the size or update the index as an array.

  • The primary list occupies more memory than the ArrayList, because the primary list stores two references for each node. One refers to the first element and the other to the next element.

30. What are the interfaces of Comparable and Comparator? List their differences.

Java provides a Comparable interface that contains only one compareTo () method. This method can sort two objects. Specifically, it returns a negative number, 0, and positive number to indicate that the input object is smaller than, equal to, and greater than the existing object.

Java provides the Comparator interface that contains the compare () and equals () methods. The compare () method is used to sort two input parameters. The return value is negative and 0. A positive value indicates that the first parameter is smaller than, equal to, or greater than the second parameter. The equals () method requires an object as a parameter to determine whether the input parameter is equal to that of Comparator. This method returns true only when the input parameter is also a Comparator and the sorting result of the current Comparator is the same.

31. What is a Java Priority Queue )?

PriorityQueue is an unbounded Queue Based on the priority heap. Its elements are sorted by natural order. During creation, we can provide it with a comparator responsible for sorting elements. PriorityQueue does not allow null values because they have no natural order, or they do not have any associated comparator. At last, PriorityQueue is NOT thread-safe. the time complexity of queuing and departure is O (log (n )).

32. Do you know big-O notation? Can you give examples of different data structures?

The Big O symbol describes how good the algorithm scale or performance is in the worst scenario when the elements in the data structure increase.

Large O symbols can also be used to describe other behaviors, such as memory consumption. Because the collection class is actually a data structure, we generally use the big O symbol to choose the best implementation based on time, memory and performance. The large O symbol can give a good description of the performance of a large amount of data.

33. How can we weigh whether unordered arrays or ordered arrays are used?

The biggest benefit of an ordered array is that the time complexity of searching is O (log n), while that of an unordered array is O (n ). The disadvantage of an ordered array is that the time complexity of the insert operation is O (n), because elements with a large value need to be moved back to place new elements. On the contrary, the insertion time complexity of unordered arrays is constant O (1 ).

34. What are the best practices of the Java Collection framework?

It is very important to select the type of the set to be used based on application requirements. For example, if the element size is fixed and can be known in advance, we should use Array instead of ArrayList.

Some collection classes allow you to specify the initial capacity. Therefore, if we can estimate the number of stored elements, we can set the initial capacity to avoid re-computing the hash value or resizing.

For type security, generics are always used for readability and robustness reasons. At the same time, the use of generics can also avoid the ClassCastException during runtime.

Using the immutable class provided by JDK as the Map key can avoid implementing the hashCode () and equals () methods for our own classes.

When programming, the interface is better than the implementation.

When the underlying set is actually null, the returned set with a length of 0 or an array does not return null.

35. What are the differences between the Enumeration interface and the Iterator interface?

Enumeration is twice the speed of Iterator and consumes less memory. However, Iterator is much safer than Enumeration because other threads cannot modify the objects in the set being traversed by iterator. At the same time, Iterator allows callers to delete elements in the underlying set, which is impossible for Enumeration.

36. What is the difference between HashSet and TreeSet?

A HashSet is implemented by a hash table. Therefore, its elements are unordered. The time complexity of the add (), remove (), and contains () methods is O (1 ).

TreeSet is implemented by a tree structure, and its elements are ordered. Therefore, the time complexity of the add (), remove (), and contains () methods is O (logn ).

37. What is the purpose of garbage collection (GC) in Java? When Will garbage collection be performed?

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

38. What will System. gc () and Runtime. gc () do?

These two methods are used to prompt the JVM to perform garbage collection. However, whether to start immediately or delay garbage collection depends on the JVM.

39. When will the finalize () method be called? What is the purpose of finalization?

Before releasing the memory occupied by an object, the garbage collector calls the finalize () method of the object. It is generally recommended to release the resources held by the object in this method.

40. If the object 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 can be recycled.

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

The JVM heap is the runtime data zone, and all class instances and arrays are allocated memory on the heap. It is created at JVM startup. The heap memory occupied by objects is collected by the automatic memory management system, that is, the garbage collector.

Heap memory is composed of survival and death objects. The surviving object is accessible to the application and will not be recycled. The dead object is the object that is inaccessible to the application and has not been recycled by the garbage collector. Until the Garbage Collector recycles these objects, they occupy heap memory.

42. What is the difference between the serial collector and the throughput collector?

The throughput collector uses the parallel version of the new generation of Garbage Collector, which is used for applications with medium-scale and large-scale data. The serial collector is sufficient for most small applications (about MB of memory is required on modern processors.

43. In Java, when can an object be reclaimed by garbage?

When the object becomes inaccessible to the application that currently uses this object, this object can be recycled.

44. Will garbage collection occur in the permanent generation of JVM?

Garbage collection does not occur for a long time. If the permanent replacement is Full or exceeds the critical value, Full GC is triggered ). If you carefully check the output information of the garbage collector, you will find that the permanent generation is also recycled. This is why the correct permanent generation size is very important to avoid Full GC.

45. What are the two exception types in Java? What are their differences?

Java has two types of exceptions: checked and unchecked. Exceptions that are not checked do not need to be declared on methods or constructors, even if the execution of methods or constructors may throw such exceptions. Moreover, exceptions that are not checked can be transmitted outside the method or constructor. On the contrary, the checked exception must be declared on the method or constructor using the throws statement.

46. What is the difference between Exception and Error in Java?

Both Exception and Error are subclasses of Throwable. Exception is used for exceptions that can be captured by a user program. Error defines exceptions that are not expected to be captured by the user program.

This article permanently updates link: https://www.bkjia.com/Linux/2018-02/151075.htm

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.