Android development engineers must take a look at the interview questions: java basic knowledge check

Source: Internet
Author: User

Android development engineers must take a look at the interview questions: java basic knowledge check

Object-Oriented Programming (OOP)
Java is a computer programming language that supports concurrency, class-based, and object-oriented. The advantages of object-oriented software development are listed below:

Code development is modular and easier to maintain and modify.
Code reuse
Enhance code reliability and flexibility
Increase the comprehensibility of the Code.

Object-Oriented Programming has many important features, such as encapsulation, inheritance, polymorphism, and abstraction. The following sections analyze these features one by one.

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 located in the same package or under different packages.
Some advantages of encapsulation are listed below:

Hides the object attributes 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.

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.

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

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.

Differences between abstraction and Encapsulation
Abstraction and encapsulation are complementary concepts. Abstract The behavior of objects. On the other hand, encapsulate the details of object behavior. Encapsulation is typically performed by hiding the internal state information of an object. Therefore, encapsulation can be seen as an abstract policy.

Common Java Problems
1. 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.

2. What is the difference between 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-in required for executing the applet. Java Development Kit (JDK) 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.

3. What does the keyword "static" 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 an instance variable of the class.
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.

4. 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.

5. What data types does Java support? What is an Automatic Disassembly box?
The basic data types supported by Java are:

byteshortintlongfloatdoublebooleanchar

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 or double to double. Otherwise, it is automatically split.

6. 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. In contrast, method override means that child classes redefine the methods of the parent class. Method override must have the same method name, parameter list, and return type. The override may not restrict access to the methods covered by it.

7. 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 the replication constructor like in C ++. The difference is that if you do not write the constructor yourself, Java will not create the default replication constructor.

8. 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.

9. What is the difference between interfaces and abstract classes?
Java provides and supports creating abstract classes and interfaces. Their implementations share the following things:
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.
You can also refer to the differences between abstract classes and interfaces in JDK 8.

10. What is value transfer and 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.

Java thread
11. What is the difference between a process and a thread?
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.

12. How can I create a thread? Which one do you like? Why??
There are three ways to create a thread:
1 inherit the Thread class
2. Implement the Runnable interface
3. 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 objects have been inherited in the application design, this requires multi-inheritance (but Java does not support multi-inheritance) and only interfaces can be implemented. At the same time, the thread pool is also very efficient and easy to implement and use.

13. Briefly explain several available states of the thread.
A thread can be in the following states during execution:

Ready (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: waiting for the lock to be obtained
Dead: The thread is finished.

14. 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 ).

The Synchronized method controls access to class members: each class instance corresponds to a lock. Each synchronized method must obtain the lock of the instance that calls this method before execution. Otherwise, the thread is blocked, once the method is executed, the lock is exclusive until the lock is released when the method is returned. Then, the blocked thread can obtain the lock and re-enter the executable status. This mechanism ensures that at most one of the member functions declared as synchronized for each instance at the same time is in the executable state (because at most one member function can obtain the corresponding lock of the instance ), this effectively avoids access to class member variables.

Some Understanding of synchronized (this)
** 1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.
2. However, when a thread accesses a synchronized (this) synchronization code block of the object, the other thread can still access the non-synchronized (this) synchronization code block of the object.
3. When a thread accesses a synchronized (this) synchronization code block of the object, access by other threads to all other synchronized (this) synchronization code blocks of the object will be blocked.
4. The third example also applies to other synchronous code blocks. That is to say, when a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.
5. The above rules apply to other Object locks. **

15. In the Monitor, how does one synchronize threads? What level of synchronization should the program perform?
The monitor and lock are used together in the Java Virtual Machine. The monitor monitors a synchronization code block and ensures 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.

16. What is a deadlock )?
A deadlock occurs when both processes are waiting for the execution of the other side to continue. The result is that both processes are in infinite waiting state.

17. 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.

Java Collection class
18. What are the basic interfaces of the Java Collection framework?
Java Collection classes provide a set of well-designed interfaces and classes that support operations on a group of objects. 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.

19. Why didn't the collection class implement the Cloneable and Serializable interfaces?
The Collection class interface specifies a group of objects called elements. Each specific implementation class of the Collection class interface can save and sort the elements in its own way. Some collection classes allow duplicate keys, and some do not.

20. What is an Iterator )?
The Iterator interface provides many methods to iterate on the collection elements. Each collection class contains
Iteration Method. The iterator can delete elements of the underlying set during iteration.
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.

21. What is the difference between Iterator and ListIterator?
Their differences are listed below:
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.

22. 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.

23. 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 and retrieve elements to/from a 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. Some important features of HashMap are its capacity, load factor, and threshold resizing ).

24. 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, two different keys may have the same hash value, so the set may think it is equal. 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.

25. What is the difference between HashMap and Hashtable?
HashMap and Hashtable both implement the Map interface, so many features are very similar. However, they have 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 ).
O generally thinks that Hashtable is a legacy class.

26. What is the difference between Array and list? When should I use Array instead of ArrayList?
The differences between Array and ArrayList are listed below:
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, the set uses automatic packing to reduce the coding workload. However, this method is relatively slow when processing a fixed-size basic data type.

27. What is the difference between ArrayList and rule list?
Both ArrayList and rule List implement the List interface, which has 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. Correspondingly, the element list stores its data in the form of a element list. Each element is linked with its previous and last 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, the size or index does not need to be recalculated 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.

You can also refer to ArrayList vs. Rule List.

28. 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. A negative number is returned, and a positive number 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.

29. What is a Java Priority Queue (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 )).

30. 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.

31. 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 ).

32. 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.

33. 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.

34. 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 ).
On the other hand, 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 ).
Garbage Collectors)

35. What is the purpose of garbage collection in Java? When Will garbage collection be performed?
The purpose of garbage collection is to identify and discard objects that are no longer used by the application to release and reuse resources.

36. 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.

37. 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.

38. 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.

39. 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.

40. What is the difference between the serial (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.

41. 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.

42. 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.

 

Related Article

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.