32 common Java base-plane questions

Source: Internet
Author: User
Tags serialization wrapper

1. What is a Java virtual machine (JVM)? Why is Java called a "platform-agnostic programming language"?

A Java Virtual machine is a virtual machine process that can execute Java bytecode. The Java source file is compiled into a bytecode file that can be executed by the Java virtual machine.

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

2. What is the relationship between JDK, JRE, and JVM?

The JDK is the Java Development Kit, which contains the compilation, runtime, and other development tools necessary to write Java programs, as well as the JRE. Development tools such as the Javac command for compiling Java programs, Java commands for starting the JVM running Java programs, the Javadoc command for generating documents, and JAR commands for packaging, and so on.

The JRE is the Java Runtime environment that provides the software environment necessary to run Java applications, including Java virtual machines (JVMS) and a rich system class library. The System class library is the Java pre-packaged functional class, just use it directly, can greatly improve the development efficiency.

The JVM is the Java virtual machine and provides the runtime environment support for the bytecode file (. Class). Simply put, the JDK contains the JRE that contains the JVM.

3. What are the data types supported by Java?

The data types supported by Java include basic data types and reference types. The basic data types are as follows.

Integer value type: Byte,short,int,long

Character type: Char

Floating-point type: float,double

Boolean Type: Boolean

integer default int, decimal type double by default. The Float and long types must be suffixed. float F = 100f, for example.

The first thing to know is that a String is a reference type, not a base type, and a variable that refers to a type declares that the variable is actually stored in memory as a reference address, and the entity is in the heap. Reference types include classes, interfaces, arrays, and so on. The String class is also final decorated.

4. What is automatic unboxing?

Automatic boxing and unpacking is the conversion between the base type and the reference type, and as to why the conversion is possible, since the base type is converted to a reference type, you can call the new object to invoke the encapsulated method in the wrapper class to convert between the basic types, or toString (of course, directly with the class name). It is easy to see that the method is static) and that if you want to store the base type in the collection, the qualified type of the generic can only be the corresponding wrapper type.

5. What is Object-oriented?

Object-oriented is a kind of thought, all things can be regarded as an object, here only discusses object-oriented programming (OOP), Java is a support concurrency, class-based and object-oriented computer programming language, object-oriented software development has the following advantages: code development modularity, easier to maintain and modify; Code reusability , enhance the reliability and flexibility of the code, and increase the readability of the code.

6. Four basic features of object-oriented?

Abstraction: The process of extracting a key feature of something in the real world and building a model for that thing. For the same thing under different requirements, the characteristics that need to be extracted may differ. The resulting abstract model typically contains: attributes (data) and operations (behaviors). This abstract model we call class, instantiate the class to get the object.

Encapsulation: Encapsulation enables classes to be independent and isolated, guaranteeing the high cohesion of classes. Exposes only properties and operations that are necessary to the outer or child class of the class. class encapsulates the implementation-dependent class modifiers (public, protected, private, and so on).

Inheritance: A reuse mechanism for existing classes. If a class inherits an existing class, the class will have all the non-private attributes (properties and operations) of the inherited class. The inheritance here refers to the inheritance of classes and the implementation of interfaces.

Polymorphism: Polymorphism is achieved on the basis of inheritance. Three elements of polymorphism: inheritance, overrides, and parent class references to child class objects. When a parent class reference points to a different subclass object, the same method is called, rendering a different behavior, which is the class polymorphism attribute. Polymorphism can be divided into compile-time polymorphism and run-time polymorphism.

Abstraction, encapsulation, inheritance, and polymorphism are the basis of object-oriented.

7. What is the difference between & and &&?

There are two ways to use the & operator: (1) bitwise AND, (2) logical AND. The && operator is short-circuiting and arithmetic.

The difference between the logic and the short-circuit is very large, although both require that the Boolean value on both sides of the operator is true the value of the entire expression is true. && is called a short-circuit operation because if the value of the expression on the left side of && is false, the expression on the right will be shorted out directly and will not be evaluated.

Most of the time we may need to use && instead of &, for example, to verify that the user's name is not NULL and is not an empty string when validating the login, it should be written as:

1username ! = null &&!username. Equals ("")

The order of the two cannot be exchanged, not the & operator, because if the first condition is not true, the equals of the string cannot be compared, otherwise a nullpointerexception exception will be generated.

Note: Logical OR operator (|) and short-circuit or operator (| | The difference is also true.

8. What is value passing and reference passing?

A value pass is a basic variable, passing a copy of the variable, changing the copy without affecting the original variable.

A reference pass is generally for an object type variable, passing a copy of the object's address, not the original object itself. It is generally assumed that the delivery within Java is a value pass, and that the delivery of an instance object in Java is a reference pass.

9. Can I access non-static variables in the static environment?

The static variable belongs to the class in Java, and it has the same value in all instances. Static variables are initialized when the class is airborne into Java virtual. If your code tries to access a non-static variable without an instance, the compiler will give an error because the variables have not been created yet and are not associated with any instances.

What does the method overrides (overriding) and method overloads (overloading) in Java mean?

Method overloads in Java occur when the same class has two or more methods with the same name but different parameters. In contrast, the method overrides the method that the subclass redefined the parent class. Method overrides must have the same method name, parameter list, and return type. The override may not restrict access to the methods it covers.

One . Does Java support multiple inheritance?

Classes in Java do not support multiple inheritance, only single inheritance (that is, a class has only one parent). However, the interface in Java supports multiple inheritance, that is, a sub-interface can have more than one parent interface. (The function of the interface is to extend the function of the object, a sub-interface inherits multiple parent interfaces, indicating that the sub-interface extends several functions, when the class implements the interface, the class expands the corresponding function).

In Java, what is a constructor method? What is a constructor method overload? What is a copy construction method?

The construction method is called when the new object is created. Each class has a method of construction. The Java compiler creates a default constructor for this class in cases where the programmer does not give the Class A constructor method.

Construction method overloading and method overloading are similar in Java. You can create multiple construction methods for a class. Each construction method must have its own unique argument list.

Java does not support copy construction methods like in C + +, because Java does not create a default copy construction method if you do not write your own construction method.

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

From the design level, abstraction is the abstraction of a class, a template design, an interface is an abstraction of behavior, and a norm of behavior.

Java provides and supports the creation of abstract classes and interfaces. Their implementations have something in common: all the methods in the interface are implicitly abstract, while abstract classes can contain both abstract and non-abstract methods.

A class can implement many interfaces, but only one abstract class is inherited. Classes can not implement all methods of abstract classes and interface declarations, and of course, in this case, the class must also be declared abstract.

An abstract class can implement an interface without providing an interface method implementation. The variables declared in the Java interface are final by default. An abstract class can contain non-final variables. The member functions in the Java interface are public by default. The member functions of an abstract class can be private,protected or public.

An interface is absolutely abstract and cannot be instantiated. An abstract class can also not be instantiated, but it can be called if it contains the main method. You can also refer to the differences between abstract classes and interfaces in JDK8.

14. Calculate 2 times 8 with the most efficient method?

2 << 3 (shift left 3 is the equivalent of multiplying by 2 by 3, and right 3 is equivalent to 2 by 3).

15. Handwriting Singleton mode (a hungry man and lazy mode) and Factory mode?

A Hungry man mode

A hungry man Singleton class. When class is initialized, it is self-instantiated
PublicClassSingleton1 {
Private default Construction Child
PrivateSingleton1() {}
Already instantiated on its own
private static final Singleton1 single = new Singleton1 ();
//Static Factory method
Public static Singleton1 getinstance() {
return single;
}
}

Lazy mode

Lazy Singleton class. Instantiated at the first call
PublicClassSingleton2 {
Private default Construction Child
PrivateSingleton2() {}
Note that there is no final
PrivateStatic Singleton2 single=Null
Static Factory method
Public synchronized static Singleton2 getinstance() {
if (single = null) {
Single = new Singleton2 ();
}
return single;
}
}

Factory mode, you can also refer to the previous design mode in the Factory mode, at the end of the link.

Interfaceifactory{
Public iproduct createproduct ();
}

ClassFactoryImplementsifactory{
Public IProduct createproduct ()
{
ReturnNew Product ();
   }
}&NBSP;

public class CLIENT{&NBSP;
  static void main  (String [] args) {
    ifactory factory=new Factory ();  
    iproduct product=factory.createproduct (); 
    product. Productmethod ();
 }
}

What is the difference between string and StringBuilder, StringBuffer?

The Java platform provides two types of strings: string and Stringbuffer/stringbuilder, which can store and manipulate strings.

Where string is a read-only string, meaning string content referenced by string cannot be changed.

The string object represented by the Stringbuffer/stringbuilder class can be modified directly. StringBuilder is introduced in Java 5, and it is exactly the same as the StringBuffer method, except that it is used in a single-threaded environment because all aspects of it are not synchronized decorated, so it is more efficient than stringbuffer To be high.

What are the Java collection frameworks? What are some of the advantages of a collection framework?

There are collections in each programming language, and the original Java version contains several collection classes: Vector, Stack, HashTable, and Array. With the extensive use of the collection, Java1.2 proposes a collection framework that encompasses all the set interfaces, implementations, and algorithms. Java has been going on for a long time with the use of generics and concurrent collection classes in a thread-safe way. It is also included in the Java bundle, blocking interfaces, and their implementations. Some of the advantages of the collection framework are as follows:
(1) Use the core collection classes to reduce development costs rather than implementing our own collection classes.
(2) with the use of rigorously tested collection framework classes, the code quality will be improved.
(3) You can reduce code maintenance costs by using the collection classes that are included with the JDK.
(4) reusability and operability.

18. What are the advantages of generics in the collection framework?

Java1.5 introduces generics, and all of the collection interfaces and implementations use it in large quantities. Generics allow us to provide a collection of object types that can be accommodated. So if you add any other type of element, it will be wrong at compile times. This avoids classcastexception at run time, because you will get an error message at compile time. Generics also make the code neat, and we don't need to use explicit conversions and instanceof operators. It also benefits the runtime because it does not produce byte-code instructions for type checking.

What are the underlying interfaces of the Java collection framework?

Collection is the root interface for the collection hierarchy. A collection represents a set of objects that are the elements of that object. The Java platform does not provide any direct implementation of this interface.

Set is a collection that cannot contain duplicate elements. This interface models the abstraction of a mathematical set and is used to represent a collection, just like a deck of cards.

A List is an ordered collection that can contain repeating elements. You can access any element by its index. The List is more like an array of length dynamic transformations.

Map is an object that maps a key to value. A map cannot contain duplicate keys, and each key can only map one value at a maximum.

Some of the other interfaces are Queue, Dequeue, SortedSet, SortedMap, and Listiterator.

20. Why Collection not inherit from cloneable and Serializable interfaces?

The Collection interface specifies a set of objects, which are the elements of the object. How to maintain these elements is determined by the specific implementation of Collection. For example, some Collection implementations such as List allow repeating elements, while others such as Set are not allowed. Many Collection implementations have a public clone method. However, it is meaningless to put it in all implementations of the collection. This is because Collection is an abstract expression, and it is important to implement.

When dealing with specific implementations, the semantics and meaning of cloning or serialization only work. Therefore, a specific implementation should decide how to clone or serialize it, or whether it can be cloned or serialized. Authorizing cloning and serialization in all implementations ultimately leads to less flexibility and more restrictions, and a particular implementation should determine whether it can be cloned and serialized.

21. Why does the Map interface not inherit the Collection interface?

Although the map interface and its implementation are part of the collection framework, the map is not a collection and the collection is not a map. Therefore, Map inheritance Collection meaningless, and vice versa.

If Map inherits the Collection interface, then where does the element go? Map contains the Key-value pair, which provides a way to extract a collection of key or value lists, but it is not suitable for a "set of object" specifications.

22. What is an iterator (Iterator)?

The Iterator interface provides many ways to iterate over a collection element. Each collection class contains an iterative method that can return an iterator instance. Iterators can delete elements of the underlying collection during the iteration, but they cannot call the collection's remove (Object Obj) directly, and can be removed through the Remove () method of the iterator.

What is the difference between Iterator and listiterator?

The Iterator can be used to traverse the set and list collection, but Listiterator can only traverse the list.

Iterator to a collection can only be forward traversal, listiterator can be either forward or back.

The Listiterator implements the Iterator interface and includes other functions. For example: adding elements, replacing elements, getting the index of the previous and subsequent elements, and so on.

How does the HashMap in Java work?

We know that the two most commonly used structures in Java are arrays and analog pointers (references), and almost all data structures can be combined using both, HashMap. In fact, HashMap is a "chain table hash."

HashMap is based on the principle of hashing, we use put (key, value) to store objects into HashMap, using get (key) to get objects from HASHMAP. When we pass the key and value to the put () method, we first call the Hashcode () method on the key, and the returned hashcode is used to locate the bucket position to store the Entry object.

25. What happens when a hashcode of two objects is the same?

Because the hashcode are the same, their buckets are in the same position and "collisions" occur. Because HashMap uses a linked list to store objects, this Entry (Map.entry object with key-value pairs) is stored in the linked list.

26. If the hashcode of the two keys is the same, how do you get the value object?

When we call the Get () method, HashMap uses the hashcode of the key object to find the bucket position, and then calls the Keys.equals () method to find the correct node in the linked list and finally finds the value object to find.

What is the importance of the hashcode () and Equals () methods?

HashMap uses the hashcode () and Equals () methods of the Key object to determine the index of the key-value pair. These methods are also used when we try to get the values from the HashMap.

If these methods are not implemented correctly, in this case, two different keys may produce the same hashcode () and Equals () outputs, HASHMAP will think they are the same, then overwrite them instead of storing them in different places.

Similarly, all collection classes that do not allow the storage of duplicate data use Hashcode () and Equals () to find duplicates, so it is important to implement them correctly. Implementations of Equals () and hashcode () should follow these rules:

If O1. equals (O2), then o1.hashcode () = = O2.hashcode () is always true.
If o1.hashcode () = = O2.hashcode (), it does not mean O1. equals (O2) will be true.

What is the difference between HashMap and HashTable?

1. HashMap is non-thread-safe and HashTable is thread-safe.

2. HashMap's keys and values allow null values to exist, while HashTable does not.

3. Because of the thread safety problem, HASHMAP efficiency is higher than HashTable.

4. HashTable is synchronous, while HashMap is not. Therefore, HASHMAP is more suitable for single-threaded environments, while HashTable is suitable for multithreaded environments.

Generally, it is not recommended to use HashTable, one is HashTable is a legacy class, the internal implementation of a lot of not optimized and redundant. Second, even in the multi-threaded environment, there are now synchronous concurrenthashmap substitution, there is no need for multithreading and use HashTable.

29. How do I decide whether to choose HashMap or TreeMap?

HashMap is the best choice for operations such as inserting, deleting, and locating elements in a Map. However, if you need to traverse an ordered set of keys, TreeMap is a better choice. Based on the size of your collection, it may be quicker to add elements to the HASHMAP, changing the map to TreeMap for an orderly key traversal.

What are the similarities and differences between ArrayList and vectors?

ArrayList and vectors are very similar in many cases.

(1) Both are index-based and internally supported by an array.

(2) Both maintain the order in which they are inserted, and we can get the elements according to the insertion order.

(3) The iterator implementations of ArrayList and vectors are fail-fast.

(4) Both ArrayList and vectors allow null values, or you can use index values to randomly access elements.

Here are the different points of ArrayList and vectors.

(1) Vector is synchronous, and ArrayList is not. However, if you seek to change the list at the time of iteration, you should use Copyonwritearraylist.

(2) ArrayList is faster than Vector, it is not overloaded because of synchronization.

(3) ArrayList is more general because we can easily get synchronization lists and read-only lists using the Collections tool class.

What is the difference between Array and ArrayList? When is it more appropriate to use an Array?

Arrays can hold basic types and objects, whereas ArrayList can only hold objects. The Array is of the specified size, and the ArrayList size is fixed. The Array does not provide as many functions as ArrayList, such as AddAll, RemoveAll, and iterator. Although ArrayList is obviously a better choice, there are times when arrays are useful, such as the following three scenarios.
(1) If the size of the list has been specified, most of the cases are stored and traversed.
(2) for traversing the base data type, although collections uses auto-boxing to alleviate the encoding task, working on a list of basic types of a specified size can also become slow.
(3) If you want to use a multidimensional array, use [] [] than List.

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

Fast failure: When you iterate a collection, a Concurrentmodification exception is thrown if another thread is modifying the collection you are accessing. Under the Java.util package is a quick failure.

Security failure: You will be able to make a copy of the underlying collection when you iterate, so you will not be affected when you modify the upper collection, and will not throw a concurrentmodification exception. Under the Java.util.concurrent package are all security failures.

If you have any questions, you can use the following wx to godless me.

Add the time to remark "Bo friends"

32 common Java base-plane 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.