Common interview questions in java -- constantly updating

java common interview questions

1 talk about your understanding of constants

Constants are final A modified variable must be assigned a value when it is defined, and the value cannot be modified. Usually, it needs to be capitalized when it is defined, and then multiple letters are separated by underscores.

2 talk about the understanding of + + and -

++And – are self increasing and self decreasing operators respectively. They are usually placed before and after integer variables, and the operation direction is from left to right

m=2Value of mThe value of the expressionanalysis
m ++32++After the variable, first participate in the operation, and then perform the self increment operation
++m33++In front of the variable, the self increment operation is carried out first, and then participate in the operation
m–12– after the variable, participate in the operation first, and then perform the self subtraction operation
–m11– in front of the variable, perform the self subtraction operation first, and then participate in the operation

3 explain the concept of short circuit

  1. &&Short circuit and: if all are true, all are false. In a short circuit and logic expression, if one expression is false, then all subsequent expressions will not participate in the operation. Because of a short circuit, the value of the whole expression is false, i.e. false; If the last expression is false, no short circuit occurs
  2. ||Short circuit or: true if true. In a short circuit or logical expression, if one expression is true, all subsequent expressions will not participate in the operation, that is, a short circuit occurs, and the value of the whole expression is true, that is, true; If the last expression is true, no short circuit occurs

4. Name 8 basic data types and their packaging classes

  1. Number type
    Integer type: byte, short, int, long (L needs to be added during output, such as 100L)
    Floating point type: float (add F when outputting, such as 3.14F), double (floating point type is double by default)

  2. Character type: char (itself is an integer, and the single output is a character, which is very special!!! The output corresponds to ASCII code)

  3. boolean type: boolean. The output result is true or false
    (Note: string is not a basic type)

5 please tell the difference between = = and equals

  1. ==Direct values are compared for basic types and memory addresses are compared for reference types
  2. Equals is a method. In string comparison, it is the content of the compared string; When comparing objects, different results are obtained according to the different logic in the equals method

6 how to define an array and what are the four key elements of the array

Define array:
①int[] arr = {1,2,3}; //Direct assignment
②int[] arr = new int[5];//5 represents the length of the array
③int[] arr = new int[]{};
Four key elements in the array: array type, array name, array element and element subscript

7. Write out common exceptions

Array subscript out of bounds:`ArrayIndexOutOfBoundException` 
Null pointer exception:`NullPointerException`
Handle digital conversion exception:`NumberFormatExcepthion`

Index out of bounds exception: Java lang.IndexOutOfBoundsException
Number format exception: Java lang.NumberFormatException
Runtime exception: RuntimeException

8 handwriting bubble sorting

//Descending sort from front to back
    System.out.print("The array sorted from front to back in descending order is:");
    for(int i = 0; i < length - 1; i ++){
    	for(int j = 0; j< length -1 -i; j ++){
    		if(nums1[j] < nums1[j + 1]){
    			int temp = nums1[j];
       		    nums1[j] = nums1[j + 1] ;
       			nums1[j + 1] = temp;
    	//Descending sort from back to front
    	System.out.print("In descending order, the array sorted from back to front is:");
    	for(int i = 0; i < length - 1; i ++){
    		for(int j = length - 1; j < i; j ++){
    			if(nums1[j] > nums1[j - 1]){
    				int temp = nums1[j];
        		    nums1[j] = nums1[j - 1] ;
        			nums1[j - 1] = temp;
    	//Ascending sort from front to back
    	System.out.print("The array sorted from top to bottom in ascending order is:");
    	for(int i = 0; i < length - 1; i ++){
    		for(int j = 0; j< length -1 -i; j ++){
    			if(nums1[j] > nums1[j + 1]){
    				int temp = nums1[j];
        		    nums1[j] = nums1[j + 1] ;
        			nums1[j + 1] = temp;
    	//Ascending sort from back to front
    	System.out.print("In ascending order, the array sorted from back to front is:");
    	for(int i = 0; i < length - 1; i ++){
    		for(int j = length - 1; j < i; j ++){
    			if(nums1[j] < nums1[j - 1]){
    				int temp = nums1[j];
        		    nums1[j] = nums1[j - 1] ;
        			nums1[j - 1] = temp;

9. Five components of JVM memory

②Method area
③VM Stack (Stack)
④Native Method Stack 
⑤Program counter

10 briefly describe your understanding of the object below

Object oriented includes three characteristics: encapsulation, inheritance and polymorphism

Object oriented, that is, you don't need to define repeated things many times, just call classes of the same type. Abstract the attributes and behaviors of things into a class, privatize their attributes and make their methods (i.e. behaviors) public, which improves the confidentiality of data and modularizes the code. This makes the code more reusable.

11 difference and scope of member variable and temporary variable

  1. Member variable: a variable defined in a class other than a method, which is stored in an object in memory. The scope is the entire class
  2. Local variable: a variable defined in a method or {} statement. It is stored in the method in the stack memory, and the scope is the method in which it is located

12. The four elements of a method's signature and the limitation of the method's return value

Four elements of signature: scope,Return value,Method name(parameter list)

If the method has a return value, the keyword return must be used in the method to return the value. The return value type is the type of the value. There can be only one return value. The return value type can be either a basic type or an object type. If the method has no return value, the return value type is void.

Method of argument 13

1. Formal parameters: when defining a method, the parameters written in the parameter list of the method are called formal parameters
2. Arguments: when a method is called, the parameters passed in at the place where the method is called are called arguments

14 value passing and reference passing of method parameters

  1. Value transfer: in the basic data type, the value of a variable is transferred. Changing the value of one variable will not affect the value of another variable
  2. Reference passing: reference data types (classes, arrays and interfaces, collectively referred to as object types). Assignment is to pass the reference of the original object to another reference. Any change in one of them will affect all other references

15 what is method overloading

In the same class, the method name is the same and the parameter list is different(Number or type)It has nothing to do with return value and access modifier

16 what is a construction method

Constructor is a special method of a class. It is used to initialize a new object of the class and call it automatically after the object is created
	By default, there is a null parameter construction method in the class. In the construction method, there are only modifiers and method names. The method name is the same as the class name, whether there is a parameter list or not
	However, if there is a parameter list, the corresponding values of the parameters need to be given in order when creating the formation

17 this keyword and super keyword

  1. This keyword is mainly used in construction methods. It refers to the currently created object. Use this keyword to call the attribute variable of the current object. When there are member variables and local variables with the same name in the class, in order to distinguish, you need to use the this keyword.
  2. super keyword is mainly used to represent the reference of the parent class and to access the properties, methods and constructors of the parent class
    Access the property of the parent class, not the private property. Use super in the subclass Attribute name
    To access the method of the parent class, you cannot access the private method of the parent class. Use super. In the subclass Method name (parameter list)
    Constructor accessing the parent class: Super (parameter list), which can only be placed in the first sentence of the constructor

18. Briefly describe the selection structure and loop structure in java

The selected structures are: if(){}else{}and switch Selection is used to deal with multi branch structures
	if If it is true in parentheses, the in curly braces will be executed; if it is false, it will be executed else In curly braces
	Switch Selection is equivalent selection, according to switch The expression value in parentheses goes with case The selected values are compared
 Cycle structure: Yes while(){},do{}while(),for Cycle three cycles
		All contain cycle conditions, cycle body, and available break To jump out of the whole cycle
		use continue To end the current loop, the loop variable needs to be initialized

19 what is inheritance

The premise of inheritance is that some classes have some same properties and methods. We extract these same properties and methods and put them in the same class to let these classes pass extends Keyword inherits this class with common properties and methods to obtain common properties and methods. This behavior is called inheritance.

Among them, inheritance can only inherit the methods and properties marked public and protected, which requires that the subclass and parent class are in the same package. If inheriting the properties and methods modified by the default permission modifier, the subclass and parent class must be in the same package and cannot inherit the methods and properties marked private. When a parent-child class has an inheritance relationship, creating a child class object will automatically call the parameterless construction method of the parent class.

20 what is encapsulation

Property privatization and method disclosure, so that the property will not be changed arbitrarily and unreasonable values will be set.
Attribute use private To declare, with get Method to get the property, using set Method value transmission

21 what is polymorphism

Polymorphism is the same reference type, which uses different instances to perform different operations. That is, after inheriting the parent class, different subclasses overwrite the objects of the parent class respectively, that is, the same method of the parent class shows different forms in the inherited subclasses.
Key: the parent class reference points to the child class object
	   Among them instanceof To determine whether an object is a type

Conditions for polymorphism (inheritance, rewriting, parent class reference pointing to child class object)

22 what is method rewriting

The parameter list remains unchanged; Scope, return value and method body have changed.
When rewriting, you can use super.Method to retain the methods of the parent class. The subclass rewrites the methods inherited by the parent class according to the requirements, and the construction method cannot be overridden

23 introduce abstract classes and abstract methods, which are the same and different from ordinary classes and ordinary methods

keyword abstract
  1. Abstract class: public abstract class name. Compared with ordinary methods, it has the same properties and methods, and the abstract methods are different.
  2. Abstract method: public abstract void method name (Pet pet). The abstract method has no method body. The abstract method must be in the abstract class, and the abstract method must be implemented in the subclass, unless the subclass is an abstract class. Ordinary classes inherit abstract classes and must implement abstract methods, that is, rewrite abstract methods. Abstract classes inherit abstract classes and can be rewritten or not.

24 introduce the interface

Interface keyword is interface Used to define an interface, implements,The user implements an interface.
Inherit first and then implement. The order cannot be changed.
Features: the interface cannot be instantiated. The implementation class must implement all methods of the interface. The implementation class can implement multiple interfaces, which are separated by commas. All variables in the interface are static constants, public static final.....

25. The execution sequence of try catch finally. What happens if a return statement appears in the catch

  1. First execute the code block of try, and then execute catch to catch the exception. If there are multiple catch blocks, the exception type needs to be preceded by the subclass exception, followed by the parent exception, and then match one by one in order. finally will be executed regardless of whether the exception is caught in the front.
  2. If a return statement appears in the catch, it will execute finally first, and then execute the return statement in the catch.

26 difference and relation between list and set

list Interfaces store objects that are not unique and orderly, that is, they can be repeated and orderly, list Only object type data can be stored, not basic type data. You can use enhanced for loop
set Interface stores unique, unordered objects. That is, it cannot be repeated, disordered, or reinforced for loop

27 difference between ArrayList and LinkList

1,ArrayList The variable length array is realized, the continuous space is allocated in memory, and the efficiency of traversing elements and random access elements is relatively high. Fast query and slow addition and deletion
2,LinkedList Using the linked list storage method, the efficiency of inserting and deleting elements is relatively high. Fast addition and deletion, slow query

28 what is serialization and deserialization

1,Serialization: store the state of an object at a certain time through a stream. Specifically, it means that the process is not the result. If serialization is to be realized, it must be realized Serializable
2,Deserialization: deserialization is the process of obtaining data from a specific stream and reconstructing an object, which means that the stored serialization information is restored to an object.

29 What are the methods of creating threads and how to start a thread

1,inherit Thread Class and override run(),Then in main Method, create a thread object and call the
//Start method to start a thread
//Create thread class object:
MyThread thread2 =new MyThread();
//Call the start method of the thread object:  
a.start( )
2,realization Runnable Interface, overriding in class Runnable In the interface run Method, in main Method, create this kind of object, and then create a thread object, and pass this kind of object as a parameter in the thread object, which is also called with the thread object start()Method to start the thread. 
//Create MyRunnable object
MyRunnable thread = new MyRunnable();
//Create current class object
Student student = new Student();
//Create thread class object 
Thread  t  =  new Thread(student );
//Call the start method of the thread object:       
t.start( )  

Tell me about your understanding of processes and threads

1,Process: the execution instance of an application. Each process has its own address space, that is, the process is the smallest unit of resource allocation.
2,Thread: CPU The basic unit of scheduling and dispatch is the smallest unit that the operating system can schedule operations. It can complete an independent sequence control process, in which multiple threads can be concurrent in one process.

31 what is multithreading

Multithreading: if multiple threads run simultaneously in a process to complete different tasks, it is called "multithreading". Multiple threads occupy alternately CPU Resources, rather than real parallel execution, the length of each thread execution is determined by the allocated time CPU Determined by the length of the time slice.
Multithreading is to complete multiple tasks synchronously, not to improve operation efficiency, but to improve resource utilization efficiency to improve the efficiency of the system. Multithreading is implemented when multiple tasks need to be completed at the same time.

The five states of 32 threads, and briefly discuss the relationship between them

Creation status: create thread object
 Ready status: start thread
 Running status: grab it cpu resources
 Blocking status: no grab cpu Resources( join perhaps sleep)
Death status: the program ends normally or external interference ends

1. Normally, there is no accident. After the thread is created, it enters the ready state, starts the thread, and then starts to seize CPU resources. When it is robbed, it will enter the running state, and when it is finished, it will enter the dead state.
2. In another case, if the CPU resources are not grabbed or the program enters sleep, it will enter the blocking state. When the blocking state is lifted, it will continue to seize the CPU resources, continue to run when it is grabbed, and enter the dead state after running.

33 three ways to create objects

  1. new keyword to create an object
Student student = new Student();

2. You can create objects (reflected methods) by calling the newInstance method of the class

Student student = Student.class.newInstance();

3. Input method of object flow

Student student = (Student) ois.readObject();

Tags: Java Interview

Posted by pete07920 on Tue, 03 May 2022 10:31:36 +0300