Java common interview basic questions

1. Is short s1 = 1; s1 = s1 + 1; wrong? short s1 = 1; s1 += 1; is wrong?

Answer: s1 = s1+1 ; It will prompt "cannot convert from int to short", 1 itself is of type int, and s1 is of short integer type, so the result of their operation is of type int. To make the expression valid, you need to Cast the result to short type
s1+=1; equivalent to s1 = (short)(s1 + 1); there is an implicit cast. So compilation will not be a problem.

2. What is the difference between int and Integer?

Answer: 8 big data types: (The data that can directly allocate memory in the stack is the basic data type)

        整型:char、short、int、long

        浮点型:float、double

        逻辑型:boolean

        字符型:char

        基本数据类型和引用数据类型:

        基本数据类型:在栈中可以直接分配内存的数据是基本数据类型。

        引用数据类型:数据的引用在栈中,但是它的对象在堆中。

        对应字节数:

        boolean:1/8个(一个字节有8bit(位)boolean只有true和false两个逻辑值,在编译后的值是用0和1来表示,他们在内存中按位来计算,只需要一位就能表示)

        byte:1个(字节型)

        char:2个(字符型,一个char只能存储一个汉字)

        short:2个(短整型)

        int:4个(整数类型)

        long:8个(长整型)

        float:4个(浮点型)

        double:8个(双精度类型 )

        java中默认的整数类型是int型,如果要定义成float型,需要在后面加上l或者L

        java中默认的浮点型是double,如果要定义成float型,需要在后面加上f或者F

        小可转大,大转小会丢失精度。

        对应的封装类:

        boolean→Boolean        

        char→Character

        byte→Byte

        short→Short

        int→Integer

        long→Long

        float→Float

        double→Double

        正题:int和Integer的区别?

        (1)Integer是int提供的封装类。int是基本数据类型中的一种。

        (2)Integer的默认值是null。int的默认值是0 。

        (3)Integer是一个对象,需要一个引用来指向这个对象,int是基本数据类型, 直接存储在内存中。

        (4)声明为Integer的变量需要实例化,声明为int的变量不需要实例化。

3. Heap and stack in java?

There are two types of memory in Java, one is heap memory and the other is stack memory.

Static storage allocation: It means that the storage space requirements of each data object at runtime can be determined at compile time, that is, the corresponding fixed memory space can be allocated to it at compile time.

Stack storage allocation: It can be called dynamic storage allocation, which is implemented by a running stack similar to a stack. Contrary to static storage allocation, in the stack storage scheme, the memory space required by the program at compile time is unknown, and the corresponding memory space can be allocated according to the required data area size only at runtime. (Stack memory is allocated on a first-in-last-out basis.)

In layman's terms, the difference between the heap and the stack: the heap is mainly used to store objects, and the stack is mainly used to execute programs.

Some basic types of variables and object reference variables defined in functions in java are allocated in the stack memory of the function. When a variable is defined in a code block, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, Java will automatically release the memory space allocated for the variable, and the memory space can be used immediately. for other purposes.

Heap memory is used to store objects and arrays created by new. Memory allocated in the heap is managed by the Java Virtual Machine's automatic garbage collector. After an array or object is generated in the heap, a special variable can also be defined in the stack, so that the value of the variable in the stack is equal to the first address of the array or object in the heap memory, and the variable in the stack becomes Array or object reference variable.

A reference variable is equivalent to a name for an array or object, and you can use the reference variable in the stack to access the array or object in the heap later in the program.

Summarize:

The stack and the heap are both places that java uses to store data in memory. (Unlike c++, java automatically manages the stack and heap, and the programmer cannot directly set the stack and heap)

heap: (object)

The Java heap is a runtime data area. The heap is responsible for garbage collection. The advantage of the heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told to the compiler in advance, because it dynamically allocates memory at runtime. Java's garbage collector will automatically collect these no longer used data. But the disadvantage is that the access speed is relatively slow due to the dynamic allocation of memory at runtime.

stack: (basic data)

The advantage of the stack is that the access speed is faster than the heap, and the stack data can be shared. But the disadvantage is that the size and lifetime of the data stored in the stack must be deterministic, which lacks flexibility. The stack mainly stores some basic types of variables.
write picture description here

4. The principle of Math.round()?
Math.round(11.5) evaluates to 12,
Math.round(11.4) evaluates to 11,
Math.round(11.6) evaluates to 12
Math.round(-11.5) evaluates to -11
Math. The result of round(-11.4) is -11
Math.round(-11.6) The result is -12
The principle is to add 0.5 to the required value and then round down.
5. What is the difference between String, StringBuffer, and StringBuilder?
They can both manipulate and store strings.
String is a read-only string, and the content of the string referenced by string cannot be changed.
String objects represented by the StringBuffer and StringBuilder classes can be modified directly.
StringBuilder was introduced after java5. The difference from StringBuffer is that StringBuilder is used in a single-threaded environment, so it is more efficient than StringBuffer.
6. The difference between overload and override. Can overloaded methods be differentiated by return type?
Overloading and rewriting are both manifestations of polymorphism. The difference between the two is:
overloading means polymorphism at compile time. It occurs in the same class, which means that in a class, methods with the same name have different parameter types or different number of parameters or different types and numbers of parameters. Note: Overloading has no special requirements on the return type.
What the rewrite is talking about: polymorphism at runtime. It occurs between the parent class and the child class, when the child class inherits the parent class and the method in the child class and the method in the parent class have the same method name, number of parameters and parameter types, and the same return type (but this After java5, the return type can be different, but it must be a subclass of the return value of the parent class. If the parent class returns the Object class, the return value of the child class can be String, etc.)
7. What is the difference between & and &&?
&: Bitwise and, convert the left and right sides into binary first, and then perform the AND operation.
&&: Logical AND. The left and right expressions are both true and true is returned, and if one of the expressions is false, the result is false
. 8. What is the difference between an abstract class and an interface?
When to use an abstract class and when to use an interface?
If you have some methods and you want some of them to have default implementations, you can use an abstract class.
If you want to implement multiple inheritance, you need to use interfaces (java does not support multiple inheritance, subclasses cannot inherit multiple classes, but can implement multiple interfaces)

An interface is an abstraction of actions, an abstract class is an abstraction of roots.
The abstract class represents what the object is, and the interface represents what the object can do.
For example: Human is an abstract class, and pig is also an abstract class. Humans have the actions of eating, drinking, and sleeping, and pigs also have the actions of eating, drinking, and sleeping. Then you can make these actions into an interface, and then separate them. to implement them concretely.

The purpose of using abstract classes: to improve code reusability. You can override the methods in the abstract class to achieve your desired purpose.
The purpose of using an interface is to embody polymorphism, so that objects implementing an interface can implement the same method in different ways.

Abstract methods: Abstract methods must be decorated with the abstract keyword. If there is an abstract method in a class, the class must be an abstract class, and the abstract class must be modified with the abstract keyword before the class. An abstract class cannot be used to create objects because an abstract class contains methods that have no concrete implementation. (Note: If a class does not contain abstract methods, it is also an abstract class if it is only modified with abstract. That is, an abstract class does not necessarily have to contain abstract methods.)

Abstract classes exist for the purpose of inheritance. If an abstract class is defined, it is not inherited. Then it is equivalent to creating this abstract class in vain.

A class that contains abstract methods is an abstract class, but it does not mean that an abstract class can only have abstract methods. Like ordinary classes, it can also have member variables and ordinary member methods.

The main differences between abstract classes and ordinary classes:
(1) Abstract methods must be public or protected, and the default is public, because private cannot be inherited.
(2) Abstract classes cannot be used to create objects.
(3) If a class inherits from an abstract class, the subclass must implement the abstract method of the superclass. If the subclass does not implement the abstract methods of the superclass, the subclass must also be defined as an abstract class.

An interface can contain variables and methods. In fact, the variables in the interface will be implicitly designated as public static final variables (can only be) methods will also be implicitly designated as public abstract methods and can only be public abstract methods.
Differences:
(1) Interfaces can be multi-inherited, abstract classes can only be single-inherited, and abstract classes can implement multiple interfaces.
(2) All methods in the interface are abstract (the default public abstract modification), and cannot have a concrete implementation. An abstract class can have ordinary methods, abstract methods, or static methods.
(3) Member variables in interfaces can only be public static final (static variables), and variables in abstract classes can be of various types.
(4) There is no constructor in the interface, and there is a constructor in the abstract class, but the constructor here cannot be used for the new object. Its function is mainly used to initialize the operation of the abstract class.

Example:
There is an interface for alerts. There is an abstract class for a door. Then, if you want to write a class of anti-theft door, you only need to inherit the abstract class of door and implement the interface of alarm.

An interface can inherit an interface, and an interface can inherit multiple interfaces, an abstract class can implement an interface, and can implement multiple interfaces, and an abstract class can inherit a concrete class.

9. Can an abstract method be static and a local method at the same time? Can it be modified by synchronized at the same time?
Answer: Abstract methods will be overridden in the future, while static methods cannot be overridden, so this is wrong. Native methods are implemented by native code, and abstract methods are not implemented, so this is also wrong.
The role of synchronized is mainly reflected in the implementation of specific methods. Similarly, abstract methods are not implemented, so this is also wrong.
10. How to use the final keyword?
Answer:
(1) Modified class: Indicates that the class cannot be inherited.
(2) Modified method: Indicates that the method cannot be overridden.
(3) Modified variable: Indicates that the value of the variable cannot be modified after assignment, constant.
11. What is the calling sequence of the object constructor?
First initialize static member variables -> then call the parent class constructor -> then initialize non-static member variables -> finally call your own constructor
12. Is it possible to call a non-static method from within a static method?
Answer: No, static methods can only access static members, and non-static methods must first create objects.
13. About GC?
Answer: GC means garbage collection. The GC function of java can automatically detect whether an object exceeds the scope so as to achieve the purpose of automatically reclaiming memory.
Effectively prevent memory leaks, GC is equivalent to a separate low-priority thread running, clearing and recycling objects that have not been used for a long time in the memory heap.
14. Conversion between data types?
Convert a string to a basic data type:
call parseXXX() of the encapsulation class corresponding to the basic data type to convert the basic data type to a
string:
Call String.valueOf(xxx) method;
15. How to realize string inversion and conversion?
Answer:

    public static String reverse(String a) {

        String newStr = ""; 
          if(a == null || a.length() <= 1) {
              return a;
          }else{
              newStr=reverse(a.substring(1))+a.charAt(0); 
              return newStr ;
          }
      }

16. Common exception handling keywords in java "throws", "throw", "try", "catch", "finally"?
Answer: Each exception in java is an object, an instance of the Throwable class or its subclasses. When an exception occurs in a method, an exception object is thrown, and the object contains exception information. The method of this object can be called to catch the exception and handle the exception.
Throw: that is, we know what exception will occur during development, and explicitly throw the exception.
throws: used to declare various exceptions that a method may throw.
try: used to specify a segment or a piece of program that needs to prevent exceptions. If there is an exception object, it can be caught by its type or processed by always executing the code block (finally).
17. Common runtime exceptions?
ArithmeticException (arithmetic exception)
ClassCastException (class conversion exception)
IllegalArgumentException (illegal parameter exception)
IndexOutOfBoundsException (out-of-bounds exception in the following table)
NullPointerException (null pointer exception)
SecurityException (safety exception)
18. What is the difference between final, finally, and finalize?
The final: modifier (keyword) has three uses:
if a class is declared final, it means that it can no longer derive new subclasses, that is, it cannot be inherited, so it is an antonym to abstract,
Declaring variables as final ensures that they will not be changed during use. Variables declared as final must be given an initial value at the time of declaration, and can only be read and unmodified in future references.
If the method is final, it can only be used and cannot be overridden in subclasses.

finally: Usually placed after try...catch, the code block is always executed, which means that the code here will be executed whether the program is executed normally or an exception occurs.

finalize: A method defined in the Object class. Java allows the use of the finalize() method to do necessary cleanup work before the garbage collector clears the object from memory. This method is called by the garbage collector when the object is destroyed. By overriding the finalize() method, system resources can be sorted out or other cleanup work can be performed.

19. What is the usage and difference of List, Set and Map?
List and set inherit from the Collection interface, but map is not.

list (list): Elements are stored in a linear fashion, and repeated elements can be stored.

The main implementation class of list:
ArrayList(): Array whose length can be changed, and the efficiency of inserting and deleting elements is slow. The retrieval efficiency is fast.
LinkedList(): Linked list data structure storage, fast insertion and deletion of elements, and slow retrieval access efficiency.
set (collection): There is no specific arrangement order of elements, and object references are stored, and there are no repeated elements.

The main implementation classes of set:
HashSet: According to the hash algorithm to access the objects in the set, the access speed is faster.
TreeSet: Implements the SortedSet interface and can sort objects in the collection.

map (map): a collection of key object and value object mapping, each element has a corresponding key (key) and value (value) object, when retrieving an element from the map, only need to give the key object to return the corresponding value object.
A map cannot contain the same key, and each key can only map one value

Main implementation classes:
hashMap: The bottom layer is implemented using data + linked list. Multiple values ​​can be placed in the same key, but the last value is taken out. (non-synchronized) Allows empty keys to be emptied.
hashTable: hashTable is the same as hashMap, the only difference is that it is thread-safe, operations such as put and get are locked, and null values ​​and null keys are not allowed.
LinkedHashMap and LinkedArrayList are similar in principle and can empty the value and empty key. (Asynchronous) Compared with hashMap, which is a singly linked list, it is a doubly linked list. (The disadvantage is that the original value will be retained)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325789616&siteId=291194637