200个最常见的JAVA面试问题(附答案)
本文内容:
- 20个最常见的JAVA面试问题(附答案)
- 13个单例模式JAVA面试问题(附答案)
- 说说JVM和垃圾收集是如何工作的(附答案)
- 说说如何避免JAVA线程死锁(附答案)
- Java中HashSet和HashMap的区别(附答案)
- Java面试中和Collection有关的10个问题(附答案)
- Java面试中和Spring相关的10个问题(附答案)
- 30个C/C++/Java面试中的常见算法问题
- Stackoverflow中回复超过20的算法问题
- 面试攻略
- 微软面试技术题(附答案)
20个最常见的JAVA面试问题(附答案)
String s = new String("Test");
does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.
@Raj suggested
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java
14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here How HashMap works in Java for detailed explanation.
15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)
16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.
18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.
19. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @Mohit
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code…
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println (“Time taken for execution is ” + (end – start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing
13个单例模式JAVA面试问题
Here they will check whether candidate has enough experience on usage of singleton or not. Does he is familiar of advantage/disadvantage or alternatives available for singleton in Java or not.
2) Can you write code for getInstance() method of a Singleton class in Java?
Most of the java programmer fail here if they have mugged up the singleton code because you can ask lots of follow-up question based upon the code they have written. I have seen many programmer write Singleton getInstance() method with double checked locking but they are not really familiar with the caveat associated with double checking of singleton prior to Java 5.
This is really nice question and I mostly asked to just quickly check whether candidate is aware of performance trade off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the time its just read only access so locking of critical section is always better option. read more about synchronization on How Synchronization works in Java
Answer: This is again related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to getInstance() will be synchronized and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton, It’s better to only synchronize critical section and not whole method. Singleton pattern is also closely related to factory design pattern where getInstance() serves as static factory method.
4) What is lazy and early loading of Singleton and how will you implement it?
This is another great Singleton interview question in terms of understanding of concept of loading and cost associated with class loading in Java. Many of which I have interviewed not really familiar with this but its good to know concept.
5) Example of Singleton in standard Java Development Kit?
This is open question to all, please share which classes are Singleton in JDK. Answer to this question is java.lang.Runtime
Answer: There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:
- Java.lang.Runtime with getRuntime() method
- Java.awt.Toolkit with getDefaultToolkit()
- Java.awt.Desktop with getDesktop()
One of the most hyped question on Singleton pattern and really demands complete understanding to get it right because of Java Memory model caveat prior to Java 5. If a guy comes up with a solution of using volatile keyword with Singleton instance and explains it then it really shows it has in depth knowledge of Java memory model and he is constantly updating his Java knowledge.
if(_INSTANCE == null){
synchronized(Singleton.class){
//double checked locking - because second check of Singleton instance with lock
if(_INSTANCE == null){
_INSTANCE = new Singleton();
}
}
}
return _INSTANCE;
}
7) How do you prevent for creating another instance of Singleton using clone() method?
This type of questions generally comes some time by asking how to break singleton or when Singleton is not Singleton in Java.
Answer: Preferred way is not to implement Clonnable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as “Can not create clone of Singleton class”.
8) How do you prevent for creating another instance of Singleton using reflection?
Open to all. In my opinion throwing exception from constructor is an option.
Answer: This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”
Another great question which requires knowledge of Serialization in Java and how to use it for persisting Singleton classes. This is open to you all but in my opinion use of readResolve() method can sort this out for you.
Answer: You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance. I have shared code on how to do it in my post Enum as Singleton in Java. This is also one of the reason I have said that use Enum to create Singleton because serialization of enum is taken care by JVM and it provides guaranteed of that.
10) When is Singleton not a Singleton in Java?
There is a very good article present in Sun's Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible. Here is the link of that article http://java.sun.com/developer/technicalArticles/Programming/singletons/
Answer: I know at least four ways to implement Singleton pattern in Java
1) Singleton by synchronizing getInstance() method
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums
15) When to choose Singleton over Static Class?
16) Can you replace Singleton with Static Class in Java?
17) Difference between Singleton and Static Class in java?
18) Advantage of Singleton over Static Class?
说说JVM和垃圾收集是如何工作的
1) objects are created on heap in Java irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.
When an Object becomes Eligible for Garbage Collection
An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
4) If an object has only live references via WeakHashMap it will be eligible for garbage collection. To learn more about HashMap see here How HashMap works in Java.
Heap Generations for Garbage Collection in Java
Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap.
New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.
Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM as discussed in my string tutorial why String is immutable in Java. There are many opinions around whether garbage collection in Java happens in perm area of java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun's implementation of JVM. You can also try this by just creating millions of String and watching for Garbage collection or OutOfMemoryError.
Types of Garbage Collector in Java
Java Runtime (J2SE 5) provides various types of Garbage collection in Java which you can choose based upon your application's performance requirement. Java 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase throughput of the application or to reduce garbage collection pause times.
1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the JVM via command line options . The tenured generation collector is same as the serial collector.
2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generationcopying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.
3) The Incremental (Sometimes called train) low pause collector: This collector is used only if -XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.
Important point to not is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.
JVM Parameters for garbage collection in Java
Garbage collection tuning is a long exercise and requires lot of profiling of application and patience to get it right. While working with High volume low latency Electronic trading system I have worked with some of the project where we need to increase the performance of Java application by profiling and finding what causing full GC and I found that Garbage collection tuning largely depends on application profile, what kind of object application has and what are there average lifetime etc. for example if an application has too many short lived object then making Eden space wide enough or larger will reduces number of minor collections. you can also control size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio among the young and tenured generation is 1:3 , you got to be careful on sizing these generation. As making young generation larger will reduce size of tenured generation which will force Major collection to occur more frequently which pauses application thread during that duration results in degraded or reduced throughput. The parameters NewSize and MaxNewSize are used to specify the young generation size from below and above. Setting these equal to one another fixes the young generation. In my opinion before doing garbage collection tuning detailed understanding ofgarbage collection in java is must and I would recommend reading Garbage collection document provided by Sun Microsystems for detail knowledge of garbage collection in Java. Also to get a full list of JVM parameters for a particular Java Virtual machine please refer official documents on garbage collection in Java. I found this link quite helpful though http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html
Full GC and Concurrent Garbage Collection in Java
Concurrent garbage collector in java uses a single garbage collector thread that runs concurrently with the application threads with the goal of completing the collection of the tenured generation before it becomes full. In normal operation, the concurrent garbage collector is able to do most of its work with the application threads still running, so only brief pauses are seen by the application threads. As a fall back, if the concurrent garbage collector is unable to finish before the tenured generation fill up, the application is paused and the collection is completed with all the application threads stopped. Such Collections with the application stopped are referred as full garbage collections or full GC and are a sign that some adjustments need to be made to the concurrent collection parameters. Always try to avoid or minimize full garbage collection or Full GC because it affects performance of Java application. When you work in finance domain for electronic trading platform and with high volume low latency systems performance of java application becomes extremely critical an you definitely like to avoid full GC during trading period.
Summary on Garbage collection in Java
1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.
2) New objects are created into young generation and subsequently moved to old generation.
3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation.
5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.
6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.
7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.
8) There is no manual way of doing garbage collection in Java
说说如何避免JAVA线程死锁(附答案)
questions starts with "What is deadlock ?"
answer is simple , when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multitasking.
How do you detect deadlock in Java ?
though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.
other way is to find it when you actually get locked while running the application , try to take thread dump , in Linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.
other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.
once you answer this , they may ask you to write code which will result in deadlock ?
here is one of my version
public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock because if thead 1 aquires lock on Sting object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.
now interviewer comes to final part , one of the most important in my view , How to fix deadlock ? or How to avoid deadlock in Java ?
if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is
the fixed version.
public void method1(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object"); synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
} public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object"); synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thread A acquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further
Java中HashSet和HashMap的区别
Java面试中和Collection有关的10个问题(附答案)
10个Java面试中和Spring相关的问题(附答案)
Some of the reader requested to provide Spring Security interview questions and answer, So i though to update this article with few of Spring security question I came across. Here are those:
How do you setup LDAP Authentication using Spring Security?
This is a very popular Spring Security interview question as Spring provides out of the box support to connect Windows Active directory for LDAP authentication and with few configuration in Spring config file you can have this feature enable. See How to perform LDAP authentication in Java using Spring Security for detailed code explanation and sample.
How do you control concurrent Active session using Spring Security?
Another Spring interview question which is based upon Out of box feature provided by Spring framework. You can easily control How many active session a user can have with a Java application by using Spring Security. See this spring security example of how to control concurrent session in Java and Spring for exact details.
<property name="newBid"/>
Ans: Spring framework is based on IOC so we call it as IOC container also So Spring beans reside inside the IOC container. Spring beans are nothing but Plain old java object (POJO).
4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called before the properties for the Bean are set.
7. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.
XmlBeanFactory factory = new XmlBeanFactory(resorce);
ApplicationContext.
|
BeanFactory
|
Here we can have more than one config files possible
|
In this only one config file or .xml file
|
Application contexts can publish events to beans that are registered as listeners
|
Doesn’t support.
|
Support internationalization (I18N) messages
|
It’s not
|
Support application life-cycle events, and validation.
|
Doesn’t support.
|
Support many enterprise services such JNDI access, EJB integration, remoting
|
Doesn’t support.
|
Question 5: What are different modules in spring?
Prototype: means a single bean definition to any number of object instances.
<property name="newBid"/>
</bean>
更多
200个最常见的JAVA面试问题(附答案)的更多相关文章
- 最常见的Java面试题及答案汇总(三)
上一篇:最常见的Java面试题及答案汇总(二) 多线程 35. 并行和并发有什么区别? 并行是指两个或者多个事件在同一时刻发生:而并发是指两个或多个事件在同一时间间隔发生. 并行是在不同实体上的多个事 ...
- 最常见的Java面试题及答案汇总(二)
上一篇:最常见的Java面试题及答案汇总(一) 容器 18. java 容器都有哪些? 常用容器的图录: 19. Collection 和 Collections 有什么区别? java.util.C ...
- 125条常见的java面试、笔试题大汇总
1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解所有问题,而仅仅是选择当中的一部分,临时不用部分细节.抽象包含两个方面,一是过程抽象. ...
- 【面试突击】- 2019年125条常见的java面试笔试题汇总(一)
1.抽象:抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部 问题,而只是选择其中的一部分,暂时不用部分细节.抽象包括两个方面,一是过程抽象,二 ...
- 【面试突击】- 2019年125条常见的java面试笔试题汇总(二)
26.什么时候用assert. assertion(断言)在软件开发中是一种常用的调试方式,很多开发语言中都支持这种机制.在实现中,assertion就是在程序中的一条语句,它对一个boolean表达 ...
- 最常见的Java面试题及答案汇总(六)
异常 74. throw 和 throws 的区别? throws是用来声明一个方法可能抛出的所有异常信息,throws是将异常声明但是不处理,而是将异常往上传,谁调用我就交给谁处理.而throw则是 ...
- 最常见的Java面试题及答案汇总(五)
Java Web 64. jsp 和 servlet 有什么区别? jsp经编译后就变成了Servlet.(JSP的本质就是Servlet,JVM只能识别java的类,不能识别JSP的代码,Web容器 ...
- 常见的Java面试题及答案整理
1. 基础篇 1. 面向对象特征:封装,继承,多态和抽象 封装封装给对象提供了隐藏内部特性和行为的能力.对象提供一些能被其他对象访问的方法来改变它内部的数据.在 Java 当中,有 3 种修饰符: p ...
- 最常见的Java面试题及答案汇总(四)
反射 57. 什么是反射? 反射主要是指程序可以访问.检测和修改它本身状态或行为的一种能力 Java反射: 在Java运行时环境中,对于任意一个类,能否知道这个类有哪些属性和方法?对于任意一个对象,能 ...
随机推荐
- hdu 3015
这个题给你一堆树,每棵树的位置x和高度h都给你 f[i]代表这棵树的位置排名,s[i]代表这棵树的高度排名 问你任意两棵树的(f[i] - f[j])*min(s[i],s[j])和 (f[i]-f[ ...
- 6.关键字static
在java中并不存在全局变量的概念,但是我们可以通过static关键字来实现一个“为全局”的概念,在java中static表示“全局”和“静态”的意思,他可以用来修饰成员变量和方法,也可以用来修饰代码 ...
- 方案dp。。
最近经常做到组合计数的题目,每当看到这种题目第一反应总是组合数学,然后要用到排列组合公式,以及容斥原理之类的..然后想啊想,最后还是不会做.. 但是比赛完之后一看,竟然是dp..例如前几天的口号匹配求 ...
- Linux (rz、sz命令行)与本地电脑 命令行上传、下载文件
Linux 与本地电脑直接交互, 命令行上传.下载文件. 一.lrzsz命令行安装: 1.rpm安装:(链接: http://pan.baidu.com/s/1cBuTm2 密码: vijf) rpm ...
- 关于国密算法 SM1,SM2,SM3,SM4 的笔记
国密即国家密码局认定的国产密码算法.主要有SM1,SM2,SM3,SM4.密钥长度和分组长度均为128位. SM1 为对称加密.其加密强度与AES相当.该算法不公开,调用该算法时,需要通过加密芯片的接 ...
- Swift可向上滑移出界面的欢迎页简单封装
使用: -(WelcomView*)welcomeView{ if (!_welcomeView) { _welcomeView = [[NSBundle mainBundle] loadNibNam ...
- sed,grep,进阶+source+export+环境变量
三剑客之sed 概括流程:从文件或管道中,可迭代读取. 命令格式: sed(软件) 选项 sed命令 输入文件 增 两个sed命令: a: 追加文本到指定行后 i: 插入到指定行前 sed -i '1 ...
- 5.Django高级
管理静态文件 项目中的CSS.图片.js都是静态文件 配置静态文件 在settings 文件中定义静态内容 STATIC_URL = '/static/' STATICFILES_DIRS = [ o ...
- Power BI Embedded 与 Bot Framework 结合的AI报表系统
最近最热门的话题莫过于AI了,之前我做过一片讲 BOTFRAMEWORK和微信 相结合的帖子 如何将 Microsoft Bot Framework 链接至微信公共号 我想今天基于这个题目扩展一下,P ...
- SQL Server 字符串拼接、读取
一.查询结果使用,字符串拼接 declare @names nvarchar(1000) declare @ParmDefinition nvarchar(1000) declare @sqltext ...