Baidu test interview questions sharing

1. What are the commonly used exception handling mechanisms in Java?

Commonly used exception handling mechanisms in Java include the following:

1) try-catch-finally statement : used to catch and handle exceptions. Place code that may throw exceptions in a try block, and then handle the exception in a catch block. Regardless of whether an exception occurs, the code in the finally block will be executed.

try {
    // 可能抛出异常的代码
} catch (ExceptionType1 e) {
    // 处理ExceptionType1类型的异常
} catch (ExceptionType2 e) {
    // 处理ExceptionType2类型的异常
} finally {
    // 无论是否发生异常,都会执行的代码
}

2) throw keyword : used to manually throw exceptions. When the program encounters a certain situation, you can use the throw keyword to throw an exception object.

if (条件) {
    throw new Exception("异常信息");
}

3) throws keyword : used to declare the types of exceptions that may be thrown by a method. When a method may throw an exception but does not handle the exception, you can use the throws keyword after the method signature to declare the exception type and let the caller handle the exception.    

public void methodName() throws ExceptionType1, ExceptionType2 {
    // 可能抛出异常的代码
}

4) Custom exception class : You can create a custom exception class inherited from Exception or RuntimeException to represent specific errors or exceptions in the program.

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

Test and development engineer tutorial: The best in the entire network in 2023, the Byte test and development boss will teach you on-site, and teach you from scratch to become a test and development engineer with an annual salary of one million_bilibili_bilibili icon-default.png?t=N7T8https://www.bilibili.com/ video/BV1hX4y187wi/?spm_id_from=333.999.0.0

 

2. Two subcategories of exceptions

Java's exception classes are all subclasses of java.lang.Throwable. It derives two subclasses: Error and  Exception . Error indicates an exception that the program cannot handle and generally should not be thrown or caught. Exception represents the exceptions that the program may handle, including checked exceptions and unchecked exceptions. Checked exceptions refer to exceptions that the compiler requires to be handled, such as IOException, SQLException, etc. Unchecked exceptions refer to exceptions that the compiler is not required to handle, such as NullPointerException, ArrayIndexOutOfBoundsException, etc.

3. Project logs. What levels are the logs divided into?

In the project, logs are divided into five levels: TRACE, DEBUG, INFO, WARN and ERROR. Among them, TRACE level logging records the most detailed information, DEBUG level logging records are the most detailed debugging information, INFO level logging records are general running information, WARN level logging records are warning information, and ERROR level logging records are error message.

4. What is the difference between equals and ==?

  • In Java, the difference between == and equals() is as follows:
  • == compares whether the values ​​of two objects are equal, while equals() compares whether the contents pointed to by the two object references are equal.
  • == compares the reference addresses of two objects, while equals() compares the contents of the two objects.
  • If a class does not override the equals() method, then calling the equals() method is equivalent to calling the equals() method of its parent class. If a class overrides the equals() method, then you need to determine whether you need to use the equals() method to compare two objects based on the specific situation.

5. Briefly talk about java’s IO stream

Java IO stream is a streaming data input/output model, which provides an efficient way to process input/output data. Java IO streams are divided into two types : byte streams  and  character streams  . Byte streams are read and written with bytes as the smallest unit, while character streams are read and written with characters as the smallest unit. Java IO stream contains many classes, such as InputStream, OutputStream, Reader, Writer, etc., each class has its specific purpose. For example, FileInputStream and FileOutputStream are used for reading and writing files, while BufferedReader and BufferedWriter can buffer data to improve reading and writing efficiency.

6. Given a scenario question for processing json files

7. What collection classes are there in Java?

Collection classes in Java are implementations of Java data structures. Java's collection class is an important part of the java.util package, which allows elements to be grouped in various ways and defines various methods to make these elements easier to manipulate. Java collection classes are Java's encapsulation and enhancement of some basic and frequently used basic classes and then provide them in the form of a class. Collection class is a class that can store multiple objects in it. It stores objects. Different collection classes have different functions and characteristics, which are suitable for different occasions and used to solve some practical problems.

Commonly used collection classes include List, Set, Map, etc. Among them, List is an ordered and repeatable collection, Set is an unordered and non-repeatable collection, and Map is a collection in the form of key-value pairs.

8. Which one is thread safe and which one is thread unsafe?

Collection classes in Java are divided into thread-safe and unsafe. Thread safety means that in a multi-threaded environment, the collection class behaves as expected without problems such as data loss or data errors. Unsafe collection classes may cause problems such as data loss and data errors in a multi-threaded environment.

Commonly used thread-safe collection classes include Vector, HashTable, Properties, etc., while commonly used thread-unsafe collection classes include ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, etc.

9. What are the functions of the thread pool?

Thread pool is a pooling technology, similar to database connection pool, HTTP connection pool, etc. The idea of ​​pooling is mainly to reduce the consumption of each acquisition and termination of resources and improve the utilization of resources. For example, in some remote areas where it is inconvenient to fetch water, people will fetch water from time to time and store it in the pool, so that they can just get it directly when using it. The same is true for thread pools. It is precisely because each creation and destruction of threads takes up too many system resources that we build such a pool to manage threads in a unified manner. Take it out of the pool when you use it, put it back when not in use, and you don’t have to destroy it. Isn’t it a lot more convenient?  

The main functions of the thread pool are as follows:   

  • Avoid memory overflow problems caused by creating too many threads.
  • Reduce resource consumption.
  • Reuse threads, conveniently manage threads and tasks, and decouple thread creation and task execution.
  • Control the number of threads running simultaneously to avoid excessive system resource usage or even crash due to too many threads.

10. Java’s garbage collection mechanism gc?

11. MySQL scenario question: Check the total number of students in a student table, check the students named Zhang in the student table, and check the student with the highest score.

1) Check the total number of students in a student table:

SELECT COUNT(*) FROM 学生表;

2) Check the student list with the surname Zhang:

SELECT * FROM 学生表 WHERE 姓名 LIKE '张%';

3) Check the student with the highest score:

SELECT * FROM 学生表 WHERE 成绩 = (SELECT MAX(成绩) FROM 学生表);

12. What are the commonly used commands in Linux? (I said vim here)

Vim is a powerful text editor that runs in the terminal and has rich functions and shortcut keys. Here are some common Vim commands:

1) Open file and save file:

  • Open file: `vim filename`
  • Save the file: In normal mode, type `:w` and press Enter
  • Save and exit: In normal mode, type `:wq` and press Enter
  • Exit without saving: In normal mode, type `:q!` and press Enter

2) Normal Mode:

Enter normal mode: press the `Esc` key.
Move the cursor: use the arrow keys or the following shortcut keys:

  • `h`: shift left
  • `j`: move down
  • `k`: move up
  • `l`: shift right

Delete characters:

  • `x`: delete the character under the cursor

copy and paste:

  • `yy`: Copy the current line
  • `p`: paste

Undo and redo:

  • `u`: Undo
  • `Ctrl + r`: redo

3) Insert Mode:

Enter insert mode:

  • `i`: insert before cursor
  • `a`: Insert after the cursor
  • `I`: Insert, at the beginning of the current line
  • `A`: Insert at the end of the current line

Exit insert mode: Press the `Esc` key

4) Visual Mode:
Enter visual mode:

  • `v`: Select text by character
  • `V`: Select text line by line
  • Copy selected text: Press `y`
  • Cut selected text: Press `x` or `d`
  • Paste: Press `p` in normal mode

5) Search and replace:

  • Search: In normal mode, enter `/`, then enter the text to be searched, and press Enter. You can use `n` and `N` to browse the search results.
  • Replace: In normal mode, enter `:%s/text to be replaced/text to be replaced/g` to replace matching items in the full text.

6) Jump and undo:

  • Jump to line number: In normal mode, enter `:`, then enter the line number and press Enter.
  • Undo: In normal mode, enter `u`.

7) Save and exit:

  • Save the file: In normal mode, type `:w` and press Enter.
  • Save and exit: In normal mode, type `:wq` and press Enter.
  • Exit without saving: In normal mode, type `:q!` and press Enter.

13. How to use vim to replace all test in a file with dev?

:%s/test/dev/g

14. How to view the ten latest modified files (use ls to view)?

ls -lt | head -n 10

What this command does is:

ls -lt: List the files and subdirectories in the current directory, sorted by modification time from newest to oldest.

  • l: Display file information in long format, including file permissions, owner, size, modification time, etc.
  • t: Sort by modification time.

head -n 10: Take the first 10 lines from the sorted file list, that is, display the ten latest modified files.

In this way, you can see a list of the ten most recently modified files, which will be displayed in the terminal in order from latest to oldest modification time. If you want to view a different number of files, just change the number in the head command.

For example, if you want to view the five most recently modified files, you can use head -n 5.

15. How to check how much disk space the current directory occupies?

du -sh .

What this command does is:

  • du: Indicates calculating disk usage.
  • s: Indicates summary results, only showing the total size of the directory and not the size of the subdirectories.
  • h: Display the file size in human-readable format, expressed in K, M, G, etc. units.
  • .: Indicates the current directory.

16. How to check how much memory is occupied by the current process?

ps aux

If you want to view the memory usage of a specific process, you can use the grep command to filter out the relevant information. Assuming you know the name of the process you are looking for, such as myprocess, you can use a command like this:

ps aux | grep myprocess

17. Do you understand top? You can use top to see how much memory is occupied?

By default, top displays all running processes, sorted by CPU usage. You can press Shift+M to sort by memory usage to see the processes using the most memory at the top of the list.

top will update the process list and resource usage in real time. You can see the PID (process identifier), memory usage (RES column), memory usage (%MEM column) and other information of each process in the list.

To exit top, press the q key.

18. Once you know a port number, how do you check the pid?

netstat -tuln | grep 端口号
sudo lsof -i :端口号

19. awk command grep command

 Test and development engineer tutorial: The best in the entire network in 2023, the Byte test and development boss will teach you on-site, and teach you from scratch to become a test and development engineer with an annual salary of one million_bilibili_bilibili icon-default.png?t=N7T8https://www.bilibili.com/ video/BV1hX4y187wi/?spm_id_from=333.999.0.0

20. You have a log file. How do you see if the log file contains error information?

grep "error" 文件名

21. What is a memory leak?

A server memory leak occurs when a server application continues to allocate memory without releasing it while running, causing the server's memory usage to gradually increase, and may eventually exhaust available memory, causing server performance degradation or crash. Memory leaks are a common software problem that usually requires careful diagnosis and repair.

22. What do you know about servers?

"Server" generally refers to hardware or software in a computer network that provides services, resources, or data to other computers or devices in order to satisfy client requests. Servers play an important role in the network and are used for various purposes such as storing and managing data, providing network services, hosting websites, and supporting applications.

Here are some common concepts about servers:

  • Hardware server: This refers to a physical server, usually a dedicated computer, used to execute server software and provide various services. Hardware servers can be in different forms such as rack servers, tower servers, blade servers, etc.
  • Virtual Server: A virtual server is a virtual instance created on a physical server through virtualization technology. A single physical server can host multiple virtual servers, each of which can run independent operating systems and applications.
  • Server software: Server software is an application installed on server hardware to provide various services, such as network services, database services, file sharing, etc. Common server operating systems include Linux, Windows Server, etc.
  • Web Server: A web server is a special type of server used to host websites and serve web content to client browsers. Common web servers include Apache, Nginx, IIS, etc.
  • Database Server: A database server is a server used to store and manage a database, allowing client applications to access and manipulate data in the database. Common database servers include MySQL, PostgreSQL, Oracle, etc.
  • Application Server: An application server is a server used to host and execute applications, typically to support business logic and back-end processing of an application. Java application servers such as Tomcat, WebLogic and application servers such as Node.js are common examples.
  • File Server: A file server is a server used to store and share files, allowing multiple users to access and share files and resources stored on the server.
  • Cloud Server: Cloud servers are virtual server instances running on a cloud computing platform. They are usually hosted and managed by a cloud service provider. Users can create, configure and expand cloud servers as needed.

Servers play a key role in enterprise and Internet applications, providing reliable resources and services that enable users to access and share information. They can be physical or virtual, with appropriate server architecture and configuration chosen based on different needs and scale.

23. How to deploy mysql service on the server?

Be confident in Baidu, there are many articles like this

24. What are the SSH commands used for?

SSH (Secure Shell) is a network protocol and encryption technology used to securely remotely access and manage computer systems. The main uses of SSH include the following aspects:

Remote Login : SSH allows users to securely log in to a remote computer system from their local computer. This is achieved by encrypting communications so sensitive data such as usernames and passwords are protected during transmission. SSH remote login is commonly used for the management of remote servers, network devices, and cloud computing instances.

File transfer : SSH can be used to securely transfer files, including uploading and downloading files. A common use case is using the scp (Secure Copy Protocol) command, which is based on SSH and is used to copy files between the local computer and a remote server.

For example, copy files from local to remote server:

scp 文件名 用户名@远程服务器IP:目标路径

Copy files from remote server to local

scp 用户名@远程服务器IP:远程文件路径 本地目标路径

Remote command execution: SSH allows users to execute commands on a remote computer without directly logging into the remote system. This is useful for automation and batch processing tasks. Use the ssh command to execute commands on the remote system, for example:

ssh 用户名@远程服务器IP "远程命令"

Port forwarding : SSH supports port forwarding, allowing users to transmit traffic in a secure communication tunnel. This is useful for protecting sensitive services and accessing restricted resources. SSH can perform local port forwarding and remote port forwarding.

Encrypted communications : SSH uses encryption technology to protect the confidentiality and integrity of communications. This makes it difficult for hackers to eavesdrop or tamper with data transmissions. SSH typically uses a public and private key pair for authentication to ensure that only authorized users can access the system.

In short, SSH is a secure remote management protocol used for tasks such as remote login, file transfer, and remote command execution. It plays an important role in network and system management, especially in protecting sensitive data and system security.

25. Tell me how to upload projects to git and how to resolve conflicts?

To upload a project to Git and resolve conflicts, the following steps are typically required. In this example, assume that you have created a Git repository on your local computer and want to push it to the remote repository, and may encounter conflicts when pushing.

Steps to upload the project to Git (push to the remote repository):

1)  Initialize the repository : If your project has not been initialized as a Git repository, please run the following command:

git init

2)  Add files : Add the files in the project to the staging area of ​​the Git warehouse:

git add .

This will add all changes to the staging area. If you only want to add a specific file, you can use git add filename.

3)  Submit changes : Submit the changes in the staging area to the local warehouse and add a commit message:

git commit -m "提交消息"

4)  Connect to the remote warehouse : Associate the local warehouse with the remote warehouse and add the address of the remote warehouse:

git remote add origin 远程仓库地址

For example:

git remote add origin https://github.com/你的用户名/你的仓库.git

5) Push to the remote warehouse : Push changes from the local warehouse to the remote warehouse:

git push -u origin 主分支名称

For example:

git push -u origin main

This will upload the project to the remote repository. The -u option is used to associate the local master branch with the remote master branch for future pushes and pulls.

Steps to resolve conflicts:

If you encounter conflicts when pushing your project, it's usually because changes in the remote repository conflict with your local changes. The steps to resolve conflicts are as follows:

①  Pull the latest changes : Before resolving conflicts, first pull the latest changes from the remote warehouse:

git pull origin 主分支名称

For example

git pull origin main

This will merge the changes from the remote repository locally.

②Resolve  conflicts : Open a file containing conflicts, and you will usually see that the conflicting parts are wrapped in tags similar to the following:

<<<<<<< HEAD 
local changes 
======= 
remote changes 
>>>>>>> remote/branch name

You'll need to manually edit the file, keeping the changes you want and removing the parts you don't. After resolving the conflict, save the file.

③  Mark as resolved : Once the conflict is resolved, use the following command to mark the file as resolved:

git add 文件名

Commit changes: Commit changes after conflict resolution

git commit -m "解决冲突"

④Push  changes : Push the changes after conflict resolution to the remote warehouse:

git push origin 主分支名称

For example:

git push origin main

 Test and development engineer tutorial: The best in the entire network in 2023, the Byte test and development boss will teach you on-site, and teach you from scratch to become a test and development engineer with an annual salary of one million_bilibili_bilibili icon-default.png?t=N7T8https://www.bilibili.com/ video/BV1hX4y187wi/?spm_id_from=333.999.0.0

 

Guess you like

Origin blog.csdn.net/MXB_1220/article/details/132879919