2021Java interview questions with answers (continuous update)

The overall preparation content:, I hope the interview can pass! ! ! !

 


Java basic core

 1. String a = "123"; String b = "123"; String c=new String("123"); What is the result of a==b? The result of a==c?  

 Answer: true, false. a==b points to the same address in the constant pool. a==c, because c is an object in the heap, and a is an object in the constant pool, so it is a different address.

Specific: https://blog.csdn.net/x18094/article/details/113873202

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

Answer: == compares the reference address of the object, and equals compares the content of the object.

3.||Which priority is higher with &&?  

 Answer: Or has a high priority, true || true && false, first calculate OR, then true && false

4. What is the difference between the underlying implementation of ArrayList and LinkedList? 

Answer: The bottom layer of arraylist is an array, and the bottom layer of linkedlist is a linked list. Linkedlist when you need to maintain the input and output order

5. What is the function of the volatile keyword?

   Answer: Ensure orderliness and memory visibility. It is used when the value needs to be updated to the main memory in time under multi-threading.

6. What is the difference between static proxy and dynamic proxy in Java?

Answer: The proxy class is written before the static proxy is compiled, and the dynamic proxy uses reflection to dynamically generate the proxy class at runtime.

7. What is the difference between String, StringBuffer and StringBuilder? 

   Answer: String is immutable, StringBuffer and StringBuilder are variable. StringBuffer is thread safe, StringBuilder is unsafe.

8. What is the underlying structure of HashMap?  

 Answer: array + linked list + red-black tree

9. How does the Put() method of HashMap work?  

 Answer: (1) Call the hash(Key) method to calculate the hash value of the Key, and then calculate the array subscript.
(2) If the hash of the key does not exist in the HashMap, insert it. If it already exists, a collision occurs.
 (3) When a collision occurs (two different string keys may calculate the same hash)
         if the keys are equal, the Value is updated.
         If the key does not want to wait, it is added to the end of the linked list.
  (4) If it is found when the linked list is placed that the length of the linked list is greater than 8 and the length of the array is greater than 64, put the key-value pair in the red-black tree (linked list to red-black tree).


10. When do the hashcode and equal methods in HashMap need to be rewritten?

    Answer: When the object is used as the key of the hashmap, the equals method must be rewritten. If equals is not written, it will not be equal.

11. What is the expansion mechanism of hashmap?  

 Answer: jdk1.8 is initially 0. When put, the capacity is expanded to 16. The load factor defaults to 0.75. When the capacity reaches 0.75, the capacity will be expanded, and the capacity will be doubled.

12. Why does hashmap use red-black trees? Why not use red-black trees directly?  

 Answer: The array is too long to insert slowly, the linked list is too long to query slowly, the binary tree is too high, and the red-black tree balances the binary tree through left-handed and right-handed color changes. If the tree is very short, there is no need to use a red-black tree, because the balanced binary tree also needs to be consumed, but it is slower.

13. What changes have been made to HashMap in jdk8?

    Answer: jdk1.8 introduces the red-black tree; when the hash collides, jdk1.8 is inserted from the tail of the linked list, and 1.7 is the head insertion method.


14. How does ConcurrentHashMap achieve thread safety?

    Answer: In JDK 1.7, the method of segmented locking is adopted; in JDK 1.8, CAS (lock-free algorithm) + synchronized is directly adopted.

Both class.forName() and classLoader can be used to load classes, the difference between them?    

Answer: The class obtained by Class.forName is the class obtained by
Classloder.loaderClass that has been initialized but has not been linked yet.
The former class.forName() not only loads the .class file of the class into the jvm, but also interprets the class and executes the static block in the class.
The classLoader only does one thing, which is to load the .class file into the jvm, it will not execute the content in the static, and only execute the static block in the newInstance.
Class.forName(name, initialize, loader) function with parameters can also control whether to load the static block. "

Class instantiation execution order?

Answer: The parent-child class static code block static{...}--->main method----->The parent-child non-static code block {...}------>Constructor------ ->General method

What is the scope of access modifiers?

Answer: Mantra: Like buns, one, two, three, four. private(1)-default(2)-protected(3)-public(4), the number represents several √

What is the difference between deep copy and shallow copy?

Answer: Deep copy will copy the reference in the object, for example, the attribute is another object. Shallow copy will not copy the attribute object, only the address.

What is serialization and deserialization?

Answer: Serialization: Object--"Byte; Deserialization: Byte--"Object
 


Spring

1. What is the difference between restcontroller and controller?

答 : restcontroller = controller + @ resposebody

2. Is the controller singleton?

Answer: Yes by default. The scope can be set to multiple cases, scope: singleton (single case), prototype (multiple cases)

3. What is the difference between filter interceptor?

Answer: The filter relies on the servlet container and is implemented based on function callbacks. It is called once when the container is initialized and can filter almost all resources including static files. The interceptor is based on a web framework such as springmvc, and uses aop based on reflection. It can be called multiple times, but it can only intercept the controller, not static files.


4. What is the life cycle of a spring bean?

Answer: Load bean definition, bean factory processor , instantiation , attribute assignment, aware interface extension , beanpost preprocessor , initialization , beanpost post processor- use and destruction of bean


5. How to initialize the spring bean?

Answer: 1. Configure init-method @Bean(init-method="xx") 2. Implement the InitializingBean method afterPropertiesSet, 3. Add @PostConstruct order: postConstruct>afterPropertiesSet>init-method


6. Briefly talk about IOC and AOP?

Answer: ioc is the inversion of permission control, creating objects is handed over to the spring container for easy management. Aop is aspect-oriented programming, which adds functions to spring objects through dynamic proxies. For example, to increase the log aspect, spirng transactions and interceptors all use aop.


7. What kind of implementation does spring's dynamic proxy use?

Answer: Spring uses jdk's dynamic proxy by default. If you want to use cglib, you can specify it through configuration files.


8. What is the difference between jdk agent and cglib agent?

Answer: jdk proxy uses reflection to generate proxy for the class that implements the interface, while cglib uses bytecode technology to generate a subclass. The former must have an implementation interface, and the latter is to generate subclasses, so the target class cannot be final.


9. There are several spring dependency injection methods, and what are they?

Answer: There are 3 common ones. Constructor injection, set method injection, attribute injection (autowire or resorce), interface injection (not commonly used)


10. The springmvc process?

Answer: Interview answer-->(The front controller (DS) receives the request, then DS calls the processor mapper HandleMapping, generates the processor object and interceptor, DS then calls the processor adapter HandleAdapter to find the corresponding handle, and calls the handler to return the model View, DS calls the view resolver to parse the view, and finally the browser renders it to the user.)

Core components:
front controller DispacherServlet
processor mapper HandleMapping
processor adapter HandleAdapter
Handle
view resolver ViewResovle

1. Send the request to the front controller DispacherServlet
2. DispacherServlet calls the processor mapper HandleMapping to generate the processor object and interceptor
3. DispatcherServlet then calls the processor adapter HandleAdapter to find the corresponding handle
4. Call the handle, return to the model view, the front controller Then call the view resolver to parse the view.
5. DispatcherServlet renders the view and returns it to the user.


11. Tell me what technologies did spring mvc use and how to achieve it?

Answer: interceptor aop technology


12. What are the annotations commonly used in Spring MVC?

Answer: @RequestMapping url mapping, @RequestBody converts request parameters to java objects, and @ResponseBody converts return parameters to json format.


13. How does springmvc transfer data to the front desk?

Answer: Put the content in it through the modelMap object, and the front end can get it through the el expression.


14. How is the springmvc interceptor written?

Answer: Implement the HandlerInterceptor interface or inherit the adapter class


15. What is WebApplicationContext?

Answer: Inherit the ApplicationContext and add some unique functions necessary for WEB applications.


16. What are the common annotations of springboot/spring?

答:@import @Component @RequestMapping @Pathvariable @Bean @Scope @Configuration @Autowired @RequestBody @ResposeBody


17. How to ensure the high availability of spring timing tasks? How to deal with two timed tasks writing tables at the same time?

Answer: In terms of database: Table primary key constraint avoids repeated insertions. If the frequency of writing is high, you can use pessimistic locking. When updating, lock for update nowait, amount type update: if it is cumulative, you can write update a = a+ In the way of b, if this operation cannot be discarded, the retry function can be added. If the frequency of writing is not high, you can use optimistic lock, increase the version number field to control, and bring the version number to update when writing.

 

18. Talk about the principle of springboot automatic configuration?

Answer: Interview answer-->(springboot annotation will introduce the suffix xxImportSelector class, which has the selectImorts method, it will look for the META-INF/spring.factories configuration file, find the automatic configuration class inside, and assemble according to the automatic configuration class.)

detailed:

@SpringBootApplication has @EnableAutoConfiguration, @EnableAutoConfiguration in @Import({EnableAutoConfigurationImportSelector.class})
his parent class AutoConfigurationImportSelector in the selectImports method will look for the META-INF/spring.factories configuration file, the configuration file automatically configures the EnableAutoConfiguration Configuration classes (such as springboot-autoconfigure META-INF/spring.factories automatic configuration classes)
are assembled according to the automatic configuration classes


19. How much does Spring cloud know?

Answer: The five major components eureka, zuul, Hystrix, ribbon, springcloud config, and service call feign


20. The difference between @Autowired/@Resource?

Answer: @Autowired is an annotation of Spring. Autowired first presses byType by default. If multiple beans are found, they are compared according to the byName method. If there are more than one, an exception is reported. @Resource is an annotation of jdk, which is assembled by name by default. If the assembly fails, it is assembled by type.

21. The difference between BeanFactory and ApplicationContext?

Answer: BeanFactory provides basic functions (instantiating objects and obtaining objects), and ApplicationContext provides more functions including aop. For loading beans, the BeanFactory is instantiated when the bean is taken, and the ApplicationContext is all instantiated when the bean is started.

 

22. What is the principle of Spring timing task execution?

Answer: Spring will look for the instance of TaskScheduler/ScheduledExecutorService first, and will use it if it exists. If it does not exist, the default configuration of ScheduledExecutorService that comes with the JDK is used.

 

23. How does spring perform multiple timing tasks?

Answer: Configure a TaskScheduler, set the thread pool size, and add it to the spring container. If not configured, multiple tasks may affect each other (waiting).

24. How does spring resolve circular dependencies?

Answer: Interview answer--"In simple terms, there is mainly a three-level cache. If a circular dependency is found in it, it will be temporarily placed in the second-level cache (indicating that there is a circular dependency), and finally placed in the first-level cache. .

1. Object A will be put into the third-level cache (singletonFactories) at the beginning, and when it is found to be dependent on B, it is also put into the third-level cache; 2. When the dependency A in B is injected, move A from the third level to the second level (delete the third Level A); 3. Put B into the first-level cache, delete the third level, and complete the injection of B; 4. Put A also into the first-level cache, delete the second-level cache, and complete the injection of A. So far, the injection of A and B is complete.

detailed: 

Suppose that there is an attribute in object A that is object B, and there is also an attribute in object B that is object A, that is, A and B are cyclically dependent.

1. Create object A, call A's structure, and save A.
2. Then prepare to inject the dependencies in object A, and find that object A depends on object B, then start to create object B.
3. Call the structure of B, and save B.
4. Then prepare to inject the structure of B, find that B depends on object A, object A has been created before, directly obtain A and inject A into B (note that object A at this time has not been completely injected successfully, object B in object A is still No injection), so B is created successfully.
5. Inject the successfully created B into A, so A is also created successfully.
So the circular dependency is solved.
  singletonObjects: singleton object cache, first level cache
  earlySingletonObjects: second level cache, singleton object cache exposed in advance. [Used to detect circular references, mutually exclusive with singletonFactories]
 singletonFactories: singleton object factory cache, three-level cache
 

step operating Contents in the three-tier list
1 Start to initialize object A

singletonFactories:

earlySingletonObjects:

singletonObjects:

2 Call the structure of A, put A into singletonFactories

singletonFactories:A

earlySingletonObjects:

singletonObjects:

3 Start to inject A's dependencies and find that A depends on object B

singletonFactories:A

earlySingletonObjects:

singletonObjects:

4 Start to initialize object B

singletonFactories:A,B

earlySingletonObjects:

singletonObjects:

5 Call the structure of B, put B into singletonFactories

singletonFactories:A,B

earlySingletonObjects:

singletonObjects:

6 Start to inject B's dependencies and find that B depends on object A

singletonFactories:A,B

earlySingletonObjects:

singletonObjects:

7

Start to initialize object A, and find that A is in singletonFactories, get A directly,

Put A into earlySingletonObjects and delete A from singletonFactories

singletonFactories:B

earlySingletonObjects:A

singletonObjects:

8 Dependency injection of object B is complete

singletonFactories:B

earlySingletonObjects:A

singletonObjects:

9

Object B is created, put B into singletonObjects,

把B从earlySingletonObjects和singletonFactories中删除

singletonFactories:

earlySingletonObjects:A

singletonObjects:B

10 对象B注入给A,继续注入A的其他依赖,直到A注入完成

singletonFactories:

earlySingletonObjects:A

singletonObjects:B

11

对象A创建完成,把A放入singletonObjects,

把A从earlySingletonObjects和singletonFactories中删除

singletonFactories:

earlySingletonObjects: 

singletonObjects:A,B

12 循环依赖处理结束,A和B都初始化和注入完成

singletonFactories:

earlySingletonObjects:

singletonObjects:A,B


表格来自:https://blog.csdn.net/lkforce/article/details/97183065?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161417812716780262598115%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=161417812716780262598115&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-2-97183065.pc_search_result_cache&utm_term=spring+%E8%A7%A3%E5%86%B3%E5%BE%AA%E7%8E%AF%E4%BE%9D%E8%B5%96

其实最关键的是,为什么会出现循环依赖?

假如说只有一级缓存singletonObjects,A对象创建后放进来,再注入B,B对象创建后也放进singletonObjects。。。。B中也有依赖A,又会创建A对象。。。。所以问题的关键是:怎么取已经创建的对象,而三级缓存的作用就是为了:可以发现是否已经有对象的实例创建好了。

@Transitional失效的情况?

答:springmvc下controller上的@Transactional不生效;检查型异常不回滚,如FileNotFoundException;只作用在public修饰符上

Springmvc 中 DispatcherServlet 初始化过程    

答:入口是web.xml中配置的ds,ds继承了HttpServletBean,FrameworkServlet,通过其中的init方法进行初始化装载bean和实例,initServletBean是实际完成上下文工作和bean初始化的方法。 
 


JVM

1.JVM里,new出来的对象是在哪个区?

答:new出来的对象放在堆里,对象的引用放在栈里。

2.说说类加载有哪些步骤?

    答:类加载分三步:加载、连接(验证、准备和解析)和初始化。

加载:class文件加载到JVM内存(静态变量、常量放到方法区),产生Class对象。

  验证:验证class文件是否格式正确。

  准备:为静态变量分配内存并设置默认的初始值

  解析:将符号引用替换为直接引用  (栈帧里的动态链接也有一步符号引用转变为直接引用)

初始化:为类的静态变量赋予正确的初始值

3.说说JVM内存模型?

答:是一种规范,与线程共享有关,堆和方法区所有线程共享,需要对其制定规则规范。主内存:java所有变量都存储在主内存中。工作内存/线程本地内存:本线程用到的变量为主存中的副本拷贝。

4.说说JVM内存结构分别放什么?

    答:堆:对象和数组、字符串常量池。方法区:常量、静态变量,运行时常量池(字面量和符号引用)。虚拟机栈:局部变量、对象引用。程序计数器:记录线程执行位置,以便下一次继续执行。

本地方法栈:是一些native方法(c++实现)

5.说说常用的JVM参数?

答:-Xms128m  -Xmx128m   Xmn1g  -XX:SurvivorRatio=4  -XX:+UseG1GC

6.说说常用的JVM调优命令?

答:jps  jstack jinfo  jmap  jstat

7.你知道反汇编吗?

答:知道。会使用javap反汇编解读i++操作原理 ,反汇编后得到JVM指令,可以通过官方文档查看JVM指令集的解释。

  javap -c  xx.class

8.说说高cpu的排查过程?

答:top命令找到进程号,用ps命令找到线程号,然后转为16进制,最后使用jstack命令找到该线程号堆栈位置。

9.堆栈溢出如何跟踪?

答:事先启动增加堆溢出跟踪日志参数-XX:+HeapDumpOnOutOfMemoryError ,用mat工具查看。

10.说说一次GC流程是怎么样的?

答:普通对象进入年轻代eden区,大对象直接进入老年代。

年轻代回收机制:

1.对象进入伊甸区,填满后触发一次minor gc,还存活的对象会复制到其中一个存活区s0并清空伊甸区。

2.当伊甸区再一次填满后,再次触发minor gc,jvm会把伊甸区和s0还存活的对象复制到另一个存活区s1,同时清空伊甸区和s0区。

3.如果复制的过程发现空间不够,就会搬到老年代。

4.如果minorgc达到15次就会搬到老年代。

11.什么是stop the world(STW)?

答:GC前会执行STW操作。线程进入JVM设置的“安全点”,暂停所有运行中的线程,stop the world,然后开始GC。

什么情况下会发生栈内存溢出?

答:递归。 

什么情况下发生堆溢出?

答:对象一直增大,不释放。 比如循环里一直list.add

g1 和 cms 区别?    

答:Cms是以获取最短回收停顿时间为目标的收集器。基于标记-清除算法实现。比较占用cpu资源,切易造成碎片。 G1是面向服务端的垃圾收集器,是jdk9默认的收集器,基于标记-整理算法实现。可利用多核、多cpu,保留分代,实现可预测停顿,可控。 
 


SQL

1.什么是三范式和反三范式?(表设计)

答:1NF:每列属性唯一;2NF主键唯一;3NF属性不能与其他表属性产生冗余。反三范式:避免过多的关联查询,可以降低范式标准,适当冗余。

2.SQL优化常见的方式?

答:避免全表扫描、合理使用索引、避免返回大量数据给客户端、避免使用游标、避免频繁创建删除临时表。

3.oracle解析器解析顺序?

答:从右到左的顺序处理FROM子句中的表名,记录数少的表写在右边作为基础表。WHERE 解析自下而上,过滤大数据量的条件放后面。

4.ORACLE分页怎么做?

答:用rownum select xx from (select xx, rownum r from test1) tt where tt.r < 100;

5.行列转换怎么做?

答:1.decode函数或者case when;2.通过map_agg函数把两个列的多行的值,映射为map;3.通过UNION语句

6.oracle怎么查树?

答:用start with conect by  。   具体:start with pid=0  connect by (prior id)=pid

7.索引查询快的原因,索引使用什么排序?

答:索引就是以空间换时间,以特定的数据结构重新存储数据,减少查询次数。mysql就是用b+树


linux

1.说说你常用的命令?

答:ps 、grep、find 、more 、less、 top、du、df、touch、chmod

2.怎么查找文件中的字符串?

 答:如果只要找到字符串的那一行,用grep字符 文件名的方式,如果要找到字符串并且要能看到上下文,就用less,用斜杠加字符串查找,用n/N往上下查找。

less -mN a.txt    查看文件,/wzx  查找字符串,n继续往下找,N网上找。g跳到第一行,G跳到最后一行,q 退出
grep wzx a.txt    查找文件内容包含字符串

3.怎么查看java进程?

答:可以用jps,也可以用ps -ef|grep
ps -ef |grep xxx    查看进程

4.怎么查看cpu占用情况?

答:top    查看cpu占用情况

5.怎么查看磁盘占用情况?

答:df    查看磁盘占用情况
du * -sh    查看当前文件夹下空间占用(包含文件夹统计) ll -h 也可以查看文件占用

6.怎么更改环境变量?

vi /etc/profile    所有用户 。  立即生效:source /etc/profile
vi ~/.bash_profile    更改当前用户环境变量。立即生效: source ~/.bash_profile

7.你知道怎么自定义一个自己的命令吗?

答:写好命令脚本,然后再环境变量增加自定义命令文件扫描路径,并且立即生效。


多线程

1.说说常用的线程池有哪些?    

答:定长线程池(FixedThreadPool)、缓存线程池(CachedThreadPool)、单线程线程池(SingleThreadExecutor)、周期线程池

2.那你知道多线程JDK8有什么新特性?

答:增加异步编程CompletableFuture。可以对返回结果进行集中处理。

3.说说ThreadPoolExecutor有几个参数,分别是什么意思?

答:7个参数。核心线程大小、最大线程数、非核心线程超时时间、单位、阻塞队列、线程工厂、拒绝策略handle

4.线程有几种拒绝策略,分别是什么?实际应该怎么使用?


答:我知道有4种。单词记不住,面试回答--》一种是直接抛异常,一直是直接丢弃任务,还有一种是抛弃等待最久的任务,另外一种我忘了。

具体:

AbortPolicy    直接抛异常,程序中断。;CallerRunsPolicy  回退调用者
DiscardOldestPolicy  抛弃队列种等待最久的任务,尝试提交   DiscardPolicy   直接丢弃任务

使用:

具体使用要根据业务来,如果业务可以支持抛异常就用抛异常,如果任务可以丢弃就用丢弃策略,没有特定的方式。我看过一个框架重写的拒绝策略是什么都不处理,具体是哪个我忘了好像是apache。

5.说说线程池工作的过程?    

答:面试回答--》1.线程池添加任务,小于核心线程数,就创建执行;2.如果大于核心数,就进入阻塞队列;3.如果阻塞队列满了,就创建非核心线程执行新添加的任务;4.如果全满了,就根据拒绝策略处理。

详细:

1.线程池创建
2.执行execute()添加任务时:
执行execute()添加任务时:
当前线程数小于核心线程数,立即创建线程并运行。
否则,进入阻塞队列等待。
如果队列满了,就会创建非核心线程并立即执行。(注意,此时阻塞队列里的任务仍然在等待)。
如果还有任务进来,并且此时运行线程大于等于最大线程数,则启动饱和拒绝策略。

3.当线程中任务执行完成时,从队列取任务。
4.如果一个线程空闲,会根据空闲时间,判断是否大于核心线程数,如果大于就销毁线程,释放内存。

用过哪些原子类,他们的原理是什么?

    答:AtomicInteger; AtomicLong; AtomicReference; AtomicBoolean;基于CAS原语实现 ,比较并交换、加载链接/条件存储,最坏的情况下是旋转锁 

创建多少线程数合适?

    答:CPU 密集型(例如:1-1000 万累加计算)则是 CUP核心数+1,如果是IO 密集型(数据库访问,远程调用)则是:最佳线程数 = (1/CPU利用率) = 1 + (I/O耗时/CPU耗时)

Threadlocal原理和作用?  

 答:作用:每个线程提供变量副本,起到线程隔离的作用。原理:每个ThreadLocal类创建一个Map,然后用线程的ID作为Map的key,实例对象作为Map的value,这样就能达到各个线程的值隔离的效果。

countdowlatch 和 cyclicbarrier 的作用?  

 答:CountDownLatch是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它运行一个或者多个线程一直处于等待状态。 CyclicBarrier要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续运行。 

使用 synchronized 修饰静态方法和非静态方法有什么区别?

    答:对象锁和类锁

死锁产生的原因?  

 答:两个以上线程,争抢对方手中的资源,而自身又不释放。
 


Redis

这边看你写了解一点redis,能说说你是怎么用的吗?    

答:redis就是说,读的次数远大于写的次数,这个使用可以用redis作为缓存,提高读的效率。

缓存击穿、缓存穿透、缓存雪崩是什么?怎么解决?

答:缓存击穿:缓存没数据,数据库有数据,一般发生在过期的时候,给数据库压力。解决:热点数据永不过期,或者解锁,第一个进来锁上,第二个线程进来等待100ms再重新获取。

缓存穿透:缓存和数据库都找不到,用户一直去访问,造成数据库压力。解决:可以给KEY设置一个null值,然后设置一个很短的时间比如5分钟过期时间或者接口层增加id递减判断,如果小于0就拦截,或者用布隆过滤器。

缓存雪崩:就是同一时间大批量的KEY都过期了。可以分散它的过期时间来解决。

布隆过滤器的原理是什么?

答:就是把可能存在的哈希数据放到一个大的bitmap中,然后一个一定不存在的数据进来,就会被过滤掉。

友情链接:

程序员搞什么副业好?https://blog.csdn.net/x18094/article/details/113782544

Guess you like

Origin blog.csdn.net/x18094/article/details/113916157