Coding With Fun
Home Docker Django Node.js Articles FAQ

Java common basics interview questions---- how many do you know?


May 31, 2021 Article blog



Hello everyone, small editor today to share some of Java's common basic knowledge interview questions, for the upcoming spring recruitment, as well as the small partners looking for a job in advance.

Recommended lessons: Java Basics Getting Started with Framework Practice, In-depth Analysis of Java Object Oriented

The size of one or eight basic data types, as well as their encapsulation classes

data type Encapsulates the class size
byte Byte 1 byte
short Short 2 bytes
int Integer 4 bytes
long Long 8 bytes
float Float 4 bytes
double Double 8 bytes
boolean Boolean /
char Character 2 bytes


Second, switch can use string as a parameter?

Variable types in switch statements can make byte, short, int, char. You can use the String type after jdk1.7, which is judged by converting String String to int through String.hashcode in switch.

The difference between equals and

The operator is used to compare whether the values of the two variables are equal, i.e. to compare whether the storage addresses of the variables are the same in memory, and the Equals() method when the String class is inherited from the Object class is used to detect whether the contents of the two objects are the same.

4. String s - new String ('abc'); How many object objects have been created?

A String-type variable s is created. I f the "abc" literal does not appear before the class is loaded here, loading here creates a String constant object corresponding to "abc". On a compliant JVM, executing the new keyword here creates a String object.

V. What are the common methods of Object?

  1. Clone() creates a copy of bin returns this object
  2. equals() judgment
  3. getclass() returns the running class of object
  4. hashcode() returns the hash code value of the object
  5. Notify() wakes up a single process waiting for an object listener
  6. NotifyAll() wakes up all processes waiting for the object listener
  7. wait() causes the current thread to wait until another thread calls the object's notify() method or the notifyAll() method
  8. ToString() returns a string representation of this object
  9. Finalize() The garbage collector calls this method when garbage collection determines that the object is not needed

Six, Java's four references, the use of the scene

  • Strong reference: The garbage collector does not recycle
  • Soft reference: If there is enough memory space, the garbage collector will not be reclaimed, and if there is not enough memory space, the garbage collector will be recycled
  • Weak references: Once only weakly referenced objects are found, the garbage collector recycles them.
  • Virtual reference: If the object is found to have a virtual reference, it is added to the reference queue associated with it before the object is recycled.

The difference between static and instance variables

Static variables are preceded by the keyword static, while instance variables are not.

An instance variable is a property that belongs to an object and must be created before the instance variable can allocate space to use the instance variable. S tatic variables do not belong to any instance object, but to classes, also known as class variables, and are allocated space as long as the program loads the bytecode of the class without creating any instance objects. In summary, static variables do not need to create any objects to be used directly, while instance variables need to create instance objects before they can be used.

Eight, the difference between Overload and Override

Overload overloads represent methods that can have more than one same name in the same class, but the list of parameters for those methods is different, i.e. the parameter parameters or parameter types are different. The return value can certainly be different when overloading, but if the list of parameters is exactly the same, overloading cannot be achieved by returning type inconsistencies, which is not possible.

Overriding Override means that a method in a child class can be identical to the method name and parameters in the parent class, and when the method is called from an object created by a child class, the method defined in the child class is called, that is, the method in the child class overrides the method of the parent class. C hildren can only throw fewer or smaller exceptions than parent classes when overwriting parent methods. The overridden method must return consistently with the overwritten method return.

Nine, the difference between abstract classes and interfaces

Abstract classes can be implemented by default methods, constructors can be used, main methods can be run, method interfaces that can be added directly to the class are not implemented by default methods, there are no constructors, they cannot be run using main methods, and methods need to be added to concretely implemented classes when adding methods to the interface.

Ten, Java object-oriented characteristics and meanings

  1. Encapsulation: The purpose of encapsulation is to achieve "high cohesion, low coupling" of programs, to prevent the effects of changes caused by program interdependence. Encapsulation is to ensure that the method of operating the same thing and related methods are placed in the same class, the method and the data of his operation in the same class;
  2. Abstraction: Abstraction is to find out the similarity and commonality of things, and then classify these things into the same category, this class only considers the similarity and commonality of these things, ignoring the factors unrelated to the current topic;
  3. Inheritance: Children inherit the contents of the parent class as their own content, you can add new content or modify the contents of the parent class and more suitable for special needs. Improved reusability and expandability of the amount procedure;
  4. Polymorphism: Polymorphism refers to the specific type of reference variable defined in the program and the method calls made through that reference variable are not certain at the time of programming, but are determined during the run of the program, that is, which class the reference variable inverts to the instance object of which class, and which class the reference variable issues is the method implemented in which class, which must be determined during the program run.

Eleven, java polymorphic implementation

interface implementation, inheriting the parent class for method overrides,

Method overloading is performed in the same class.

Twelve, the difference between runtime exceptions and general exceptions

An exception indicates an abnormal state that may occur while the program is running. R un-time exceptions represent exceptions that may be encountered in the typical operation of a virtual machine and are a common run error. The java compiler requires that the method must declare a non-run-time exception that might be thrown, but it does not require that it declare an exception that throws an uncaught exception.

Thirteen, Java language how to handle exceptions, throws, throws, try catch finally means, try block can throw exceptions?

Java handles exceptions through an object-oriented approach, categorizes a variety of exceptions, and provides a good interface. I n Java, each exception is an object, an instance of a Throwable class or other subclass. When one

When an exception occurs, an exception object is thrown that contains exception information, and the method that calls the object can catch the exception and handle it. J ava's exception handling is achieved through five keywords: try, catch, throw, throws, and final. In general, a program is executed with try, and if an exception occurs, an exception is thrown, which allows you to catch it by its type, or finally (finally) to be handled by the default processor.

Use terry to specify a program that prevents all "exceptions." Immediately after the try program, you should include a catch clause to specify the type of "exception" you want to catch.

The throw statement is used to explicitly throw an "exception";

Throws are used to indicate various "exceptions" that a member function might throw;

Finally ensures that a piece of code is executed no matter what "exception" occurs;

You can write a try statement outside a member function call, and write another try statement inside that member function to protect other code. Whenever a try statement is encountered, the framework for the Exception is placed on the stack until all the try statements are complete;

If the next-level try statement does not handle an "exception," the stack expands until it encounters a try statement that handles such an "exception."

Fourteen, try catch finally, try there is a return, finally still execute?

  1. The final statement is always executed;
  2. If there is a return statement in try, catch, and there is no return in finally, modifying the data in finally, except for wrapper types and static variables, global variables, will have no effect on the variables returned in try, catch (packaging type, static variables change, global variables);
  3. Try not to use the return statement in finally, and if you use it, ignore the return statements in try, catch, and ignore exceptions in try, catch, masking errors;
  4. Avoid throwing exceptions again in finally, and once an exception occurs in finally, code execution throws exception information in finally, and exceptions in try, catch are ignored.

Fifteen, the difference between final, final, and finalize in Java

  • final is used to declare properties, methods, and classes, representing properties that are immutable, methods are not overwritten, classes are not inheritable, and internal classes must be defined as final types, for example, a piece of code...
  • Finally is part of the structure of the exception handling statement, which means that it is always executed;
  • Finalize is a method of the Object class that calls this method of the reclaimed object when the garbage collector executes, and can override other resource collections when this method provides garbage collection, such as closing files, and so on. JVM does not guarantee that this method will always be called.

16, String, String Buffer and StringBuilder

  • String represents a string whose content is non-modifiable, and StringBuffer represents a string whose content can be modified;
  • String overrides the equals() method and hashcode() method, and StringBuffer does not override both methods, so there is a problem when the StringBuffer object is stored in the java collection class;
  • StringBulider also represents strings where content can be modified, but its threads are unsafe and efficient to run.

Seventeen, error and exception are different

  • error indicates a serious problem that is likely to recover but is difficult and cannot be addressed by the program;
  • exception represents a design or implementation problem.

Eighteen, the exception handling mechanism and simple principles and applications in Java

When a JAVA program violates JAVA's semantic rules, the JAVA virtual machine represents the error that occurred as an exception. Violations of semantic rules include two scenarios:

One is the semantic check built into the JAVA class library. F or example, an array underlying marker crosses the line and causes IndexOutOfBoundsException; NullPointerException is raised when you access an object of null.

In another case, JAVA allows programmers to extend this semantic check, where they can create their own exceptions and freely choose when to throw them with the throw keyword. All exceptions are subclasses of java.lang.Thowable.

Nineteen, common runtime exceptions

System exceptions are subclasses of RuntimeException, and common system exceptions are:

  • ArrayIndexOutOfBoundsException - Array cross-border access
  • ClassCastException - Type conversion exception
  • NullPointerException - An element that attempts to access a variable, method, or empty array of an object
  • IllegalArgumentException - The parameters of the method are not valid
  • NoClassDefoundException - The REFERENCED CLASS COULD NOT BE FOUND BY THE JAVA RUNTIME SYSTEM

Twenty, the elements inside set can not be repeated, with what method to distinguish between duplication or not?

  • The element in set is the only one that cannot be repeated, and whether the element reuses the equals() method is used to determine.
  • The equals() method and the method determine whether the reference value points to the same object equals() is overwritten in the class, returning the true value if the contents and types of the two separate objects match.

The difference between HashMap and Hashtable

  1. Hashtable is based on the Dictionary class, and HashMap is an implementation class for the Map interface;
  2. Hashtable is thread-safe, i.e. synchronous;
  3. HashMap can use empty values as keys or values.

22, HashMap, LinkedHashMap, TreeMap

  1. HashMap stores data based on the hashcode value of the key, according to which the key can get its value directly, with fast access speed, and the data obtained is completely random;
  2. LinkedHashMap saves the order in which records are inserted, and when traversing with Iterator, the first thing you get is definitely the data you insert first, which can be constructed with parameters and sorted by the number of applications;
  3. TreeMap implements the SortMap interface, which sorts the records it holds by key. The default is ascending sorting, or you can specify a sort comparator, which is a sorted record when traversed.

Twenty-three, HashMap, LinkedHashMap, Concurrent HashMap, ArrayList, LinkedList underlying implementation.

  1. HashMap is a combination of two large arrays of structures and lists in a java data structure. H ashMap is the underlying array, and each item in the array is a linked list. The program first determines where entry is stored in the array based on key's hashcode() method return value, and if there are no elements in that location, the element is placed at that location, equals are called if the keys of the two Entry are the same, the return value is true, the original value is overwritten, and false is returned to form an Entry entry chain, located at the head.
  2. The underlying implementation of ArrrayList is an array, and when you perform the add operation, you first check whether the array size can accommodate new elements and expand if it is not enough. The original data is then copied to the new array.
  3. At the bottom of LinkedList is a list that implements the same checks as the operations in the data structure, and the insertion is ordered.
  4. LinkedHashMap's underlying structure is a double-linked list, with other logical processing consistent with HashMap, no lock protection, and risky multithreaded use.
  5. ConcurrentHashMap is a segment array structure and hashEntry array structure that acts as a lock in ConcurrentHashMap, which stores key-to-value pairs of data. T he structure of the segment is an array and a list, and there is a HashEntry in a segment, and each HashEntry is an element of the list structure. W hen you modify the data in HashEntry, you need to get the segment lock for it first. Each ConcurrentHashMap has 16 segments by default.

Twenty-four, iterator Iterator

Iterator provides a unified interface that traverses the elements of the operation collection, and the Collection interface implements the Iterator interface. Each collection returns an instance by implementing the iterator() method in the Iterator interface, and then iterates on the element, but the method of the collection cannot be used to delete the element when iterating the element, otherwise an exception is thrown and can be deleted using the remove() method in the Iterator interface.

The characteristics and usage of Map, Set, List, Queue, stack.

1, Map is stored in the form of key value pairs, where key is the only non-repeatable, value can be repeated, when the inserted value is the same key, then added will be the existing overlay. He has several specific implementation classes, including Treemap and HashMap, TreeMap is ordered, and HashMap is out of order.

2, List orderly, repeatable

|–ArrayList

The underlying data structure is an array, with fast queries, slow additions and deletions, unsafe threads, and high efficiency

|–Vector

The underlying data structure is an array, with fast queries, slow additions and deletions, unsafe threads, and high efficiency

|–LinkedList

The underlying data structure is a linked list, slow query, addition and deletion blocks, thread safety, low efficiency

3, Set disordered, unique

|–HashSet

The underlying data structure is a hash table

How to ensure the uniqueness of an element:

Depends on two methods, hashCode() and equals()

|–LinkedHashSet

The underlying data structure is a list and hash table, which guarantees that the elements are ordered and that the hash tables are unique

|-TreeSet the underlying data structure is a red and black tree,

How to ensure the ordering of elements:

Natural sorting: Lets the class to which the element belongs implement the Comparable interface

Comparator sorting: Lets the collection receive an implementation class object from Comparator

How to ensure the uniqueness of an element:

It is determined by whether the return value of the comparison is 0

4, Query queue follows the principle of first-in, first-out, not allowed to insert null values, which provides the corresponding way to enter and out of the team, it is recommended to use the offer() method to add elements, the use of poll() method to delete elements

5, Stack follows the principle of last-in, first-out, inherited from Vector. He extends the Vector class with five operations, which provide push and pop operations, as well as the peek() method to the stack vertex, to test whether the stack is empty

6, the use of methods:

List is recommended when it comes to stack, queue, and so on

It is recommended to use LinkedList for quick insertion and deletion of elements

ArrayList is recommended for elements that require quick random access

Twenty-six, Collection package structure

Collection is the parent interface of a collection class and is a single-column collection. The main interfaces that inherited him were Set and List.

The sub-interfaces of the Set interface are: HashSet, TreeSet

The sub-interfaces of the List interface are: Arraylist, LinkedList, Vector

27, the difference between Collection and Collections.

Collection is the parent interface of a collection class, inheriting its interfaces such as Set and List;

Collections is a help class for collection classes that provides a series of static methods for searching, sorting, thread safety, and more.

Twenty-eight, colection framework to implement the comparison of what interfaces to implement?

comparable: Only the compareTo() method is included

comparator:compare() and equals()

Twenty-nine, the structure of the Collection framework

Collection Framework refers in general to several classes and interfaces of the java.util package. such as Collection, List, ArrayList, LinkedList, Vector (Auto Growth Array), HashSet, HashMap, etc.;

The classes in the collection framework are mainly encapsulated by typical data structures, such as dynamic arrays, lists, stacks, collections, hash tables, etc.

The set framework is similar to the tool classes often used in programming, making coding a focus on the implementation of the business layer without the need to implement the relevant details from the bottom - "encapsulation of data structures" and "implementation of typical algorithms".

Thirty, the difference between a quick failure (fail-fast) and a security failure (fail-safe).

Iterator's security failure is based on making a copy of the underlying collection, so it is not affected by the source collection modification. All collection classes under the util package fail quickly, and all classes below the util.concurren package fail safely.


Recommended lessons: Java development examples: Tank Wars games, Java zero-based io flow details