115 Java Interview Questions and Answers - The Ultimate List (Part 1)

In this article we are going to discuss the different types of interview questions in Java interviews that allow employers to test a candidate's Java and general object-oriented programming skills. The following chapters are divided into upper and lower parts. The first part will discuss object-oriented programming and its characteristics, common questions about Java and its functions, Java's collection classes, and garbage collectors. The second part mainly discusses exception handling, Java Applets, Swing, JDBC, Remote Method Invocation (RMI), Servlets and JSPs.

 

Object Oriented Programming (OOP)

Java is a concurrent, class-based and object-oriented computer programming language. The advantages of object-oriented software development are listed below:

  • Code development is modular, easier to maintain and modify.
  • Code reuse.
  • Enhance the reliability and flexibility of your code.
  • Increase the understandability of the code.

Object-oriented programming has many important features, such as: encapsulation, inheritance, polymorphism and abstraction. In the following sections we will analyze these features one by one.

package

Encapsulation provides objects with the ability to hide internal features and behavior. Objects provide methods that can be accessed by other objects to change data within it. In Java, there are 3 modifiers: public, private and protected. Each modifier grants different access rights to other objects in the same package or under different packages.

Some of the benefits of using encapsulation are listed below:

  • Protects the state inside an object by hiding its properties.
  • The usability and maintainability of the code is improved because the behavior of objects can be individually changed or extended.
  • Prohibiting bad interactions between objects improves modularity.

Refer to this document for more details and examples on encapsulation.

polymorphism

Polymorphism is the ability of a programming language to present the same interface to different underlying data types. An operation on a polymorphic type can be applied to values ​​of other types.

inherit

Inheritance provides objects with the ability to obtain fields and methods from base classes. Inheritance provides reusable lines of code, and it is also possible to add new features to existing classes without modifying the class.

abstract

Abstraction is the step of separating ideas from concrete instances, so classes are created based on their functionality rather than implementation details. Java supports creating abstract classes that expose only the interface but not the method implementations. The main purpose of this abstraction technique is to separate the behavior of the class from the implementation details.

The difference between abstraction and encapsulation

Abstraction and encapsulation are complementary concepts. On the one hand, abstraction is concerned with the behavior of objects. Encapsulation, on the other hand, focuses on the details of an object's behavior. Generally, encapsulation is achieved by hiding the internal state information of the object. Therefore, encapsulation can be regarded as a strategy used to provide abstraction.

Common Java Questions

1. What is the Java Virtual Machine? Why is Java called a "platform independent programming language"?

The Java Virtual Machine is a virtual machine process that can execute Java bytecode. Java source files are compiled into bytecode files that can be executed by the Java virtual machine.

Java was designed to allow applications to run on any platform without requiring programmers to individually rewrite or recompile for each platform. The Java Virtual Machine makes this possible because it knows the instruction length and other characteristics of the underlying hardware platform.

2. What is the difference between JDK and JRE?

A Java Runtime Environment (JRE) is a Java virtual machine that will execute Java programs. It also contains the browser plug-ins required to execute the applet. The Java Development Kit (JDK) is a complete Java software development kit that includes the JRE, compiler and other tools (such as JavaDoc, Java debugger) that allow developers to develop, compile, and execute Java applications.

3. What does the "static" keyword mean? Is it possible to override a private or static method in Java?

The "static" keyword indicates that a member variable or member method can be accessed without the instance variable of the owning class.
Static methods in Java cannot be overridden because method overriding is dynamically bound at runtime, while static methods are statically bound at compile time. A static method is not associated with any instance of the class, so it is not conceptually applicable.

4. Is it possible to access non-static variables in static environment?

A static variable belongs to a class in Java, and its value is the same in all instances. When a class is loaded by the Java virtual machine, static variables are initialized. If your code tries to access non-static variables without an instance, the compiler will complain, because these variables have not yet been created and are not associated with any instance.

5. What are the data types supported by Java? What is automatic unboxing?

The 8 basic data types supported by the Java language are:

  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

Autoboxing is a conversion done by the Java compiler between primitive data types and the corresponding object wrapper types. For example: convert int to Integer, double convert to double, and so on. The opposite is automatic unboxing.

6. What does Overriding and Overloading mean in Java?

Method overloading in Java occurs when two or more methods in the same class have the same method name but different parameters. In contrast, method overriding says that a subclass redefines a method of the superclass. Method overrides must have the same method name, parameter list and return type. An overrider may not restrict access to the methods it overrides.

7. In Java, what is a constructor? What is constructor overloading? What is a copy constructor?

When a new object is created, the constructor is called. Every class has a constructor. In the case where the programmer does not provide a constructor for the class, the Java compiler will create a default constructor for the class.

Constructor overloading is very similar to method overloading in Java. Multiple constructors can be created for a class. Each constructor must have its own unique parameter list.

Java doesn't support copy constructors like C++ does, the difference is because Java doesn't create a default copy constructor if you don't write your own.

8. Does Java support multiple inheritance?

No, Java does not support multiple inheritance. Each class can only inherit from one class, but can implement multiple interfaces.

9. What is the difference between an interface and an abstract class?

Java provides and supports creating abstract classes and interfaces. Their implementations have something in common, the differences are:

  • All methods in an interface are implicitly abstract. An abstract class can contain both abstract and non-abstract methods.
  • A class can implement many interfaces, but can only inherit from one abstract class
  • 类如果要实现一个接口,它必须要实现接口声明的所有方法。但是,类可以不实现抽象类声明的所有方法,当然,在这种情况下,类也必须得声明成是抽象的。
  • 抽象类可以在不提供接口方法实现的情况下实现接口。
  • Java接口中声明的变量默认都是final的。抽象类可以包含非final的变量。
  • Java接口中的成员函数默认是public的。抽象类的成员函数可以是private,protected或者是public。
  • 接口是绝对抽象的,不可以被实例化。抽象类也不可以被实例化,但是,如果它包含main方法的话是可以被调用的。

也可以参考JDK8中抽象类和接口的区别

10.什么是值传递和引用传递?

对象被值传递,意味着传递了对象的一个副本。因此,就算是改变了对象副本,也不会影响源对象的值。

对象被引用传递,意味着传递的并不是实际的对象,而是对象的引用。因此,外部对引用对象所做的改变会反映到所有的对象上。

Java线程

11.进程和线程的区别是什么?

进程是执行着的应用程序,而线程是进程内部的一个执行序列。一个进程可以有多个线程。线程又叫做轻量级进程。

12.创建线程有几种不同的方式?你喜欢哪一种?为什么?

有三种方式可以用来创建线程:

  • 继承Thread类
  • 实现Runnable接口
  • 应用程序可以使用Executor框架来创建线程池

实现Runnable接口这种方式更受欢迎,因为这不需要继承Thread类。在应用设计中已经继承了别的对象的情况下,这需要多继承(而Java不支持多继承),只能实现接口。同时,线程池也是非常高效的,很容易实现和使用。

13.概括的解释下线程的几种可用状态。

线程在执行过程中,可以处于下面几种状态:

  • 就绪(Runnable):线程准备运行,不一定立马就能开始执行。
  • 运行中(Running):进程正在执行线程的代码。
  • 等待中(Waiting):线程处于阻塞的状态,等待外部的处理结束。
  • 睡眠中(Sleeping):线程被强制睡眠。
  • I/O阻塞(Blocked on I/O):等待I/O操作完成。
  • 同步阻塞(Blocked on Synchronization):等待获取锁。
  • 死亡(Dead):线程完成了执行。

14.同步方法和同步代码块的区别是什么?

在Java语言中,每一个对象有一把锁。线程可以使用synchronized关键字来获取对象上的锁。synchronized关键字可应用在方法级别(粗粒度锁)或者是代码块级别(细粒度锁)。

15.在监视器(Monitor)内部,是如何做线程同步的?程序应该做哪种级别的同步?

监视器和锁在Java虚拟机中是一块使用的。监视器监视一块同步代码块,确保一次只有一个线程执行同步代码块。每一个监视器都和一个对象引用相关联。线程在获取锁之前不允许执行同步代码。

16.什么是死锁(deadlock)?

两个进程都在等待对方执行完毕才能继续往下执行的时候就发生了死锁。结果就是两个进程都陷入了无限的等待中。

17.如何确保N个线程可以访问N个资源同时又不导致死锁?

使用多线程的时候,一种非常简单的避免死锁的方式就是:指定获取锁的顺序,并强制线程按照指定的顺序获取锁。因此,如果所有的线程都是以同样的顺序加锁和释放锁,就不会出现死锁了。

Java集合类

18.Java集合类框架的基本接口有哪些?

Java集合类提供了一套设计良好的支持对一组对象进行操作的接口和类。Java集合类里面最基本的接口有:

  • Collection:代表一组对象,每一个对象都是它的子元素。
  • Set:不包含重复元素的Collection。
  • List:有顺序的collection,并且可以包含重复元素。
  • Map:可以把键(key)映射到值(value)的对象,键不能重复。

19.为什么集合类没有实现Cloneable和Serializable接口?

集合类接口指定了一组叫做元素的对象。集合类接口的每一种具体的实现类都可以选择以它自己的方式对元素进行保存和排序。有的集合类允许重复的键,有些不允许。

20.什么是迭代器(Iterator)?

Iterator接口提供了很多对集合元素进行迭代的方法。每一个集合类都包含了可以返回迭代器实例的
迭代方法。迭代器可以在迭代的过程中删除底层集合的元素。

克隆(cloning)或者是序列化(serialization)的语义和含义是跟具体的实现相关的。因此,应该由集合类的具体实现来决定如何被克隆或者是序列化。

21.Iterator和ListIterator的区别是什么?

下面列出了他们的区别:

  • Iterator可用来遍历Set和List集合,但是ListIterator只能用来遍历List。
  • Iterator对集合只能是前向遍历,ListIterator既可以前向也可以后向。
  • ListIterator实现了Iterator接口,并包含其他的功能,比如:增加元素,替换元素,获取前一个和后一个元素的索引,等等。

22.快速失败(fail-fast)和安全失败(fail-safe)的区别是什么?

Iterator的安全失败是基于对底层集合做拷贝,因此,它不受源集合上修改的影响。java.util包下面的所有的集合类都是快速失败的,而java.util.concurrent包下面的所有的类都是安全失败的。快速失败的迭代器会抛出ConcurrentModificationException异常,而安全失败的迭代器永远不会抛出这样的异常。

23.Java中的HashMap的工作原理是什么?

Java中的HashMap是以键值对(key-value)的形式存储元素的。HashMap需要一个hash函数,它使用hashCode()和equals()方法来向集合/从集合添加和检索元素。当调用put()方法的时候,HashMap会计算key的hash值,然后把键值对存储在集合中合适的索引上。如果key已经存在了,value会被更新成新值。HashMap的一些重要的特性是它的容量(capacity),负载因子(load factor)和扩容极限(threshold resizing)。

24.hashCode()和equals()方法的重要性体现在什么地方?

Java中的HashMap使用hashCode()和equals()方法来确定键值对的索引,当根据键获取值的时候也会用到这两个方法。如果没有正确的实现这两个方法,两个不同的键可能会有相同的hash值,因此,可能会被集合认为是相等的。而且,这两个方法也用来发现重复元素。所以这两个方法的实现对HashMap的精确性和正确性是至关重要的。

25.HashMap和Hashtable有什么区别?

  • HashMap和Hashtable都实现了Map接口,因此很多特性非常相似。但是,他们有以下不同点:
  • HashMap允许键和值是null,而Hashtable不允许键或者值是null。
  • Hashtable是同步的,而HashMap不是。因此,HashMap更适合于单线程环境,而Hashtable适合于多线程环境。
  • HashMap提供了可供应用迭代的键的集合,因此,HashMap是快速失败的。另一方面,Hashtable提供了对键的列举(Enumeration)。
    • 一般认为Hashtable是一个遗留的类。

26.数组(Array)和列表(ArrayList)有什么区别?什么时候应该使用Array而不是ArrayList?

下面列出了Array和ArrayList的不同点:

  • Array可以包含基本类型和对象类型,ArrayList只能包含对象类型。
  • Array大小是固定的,ArrayList的大小是动态变化的。
  • ArrayList提供了更多的方法和特性,比如:addAll(),removeAll(),iterator()等等。
  • 对于基本类型数据,集合使用自动装箱来减少编码工作量。但是,当处理固定大小的基本数据类型的时候,这种方式相对比较慢。

27.ArrayList和LinkedList有什么区别?

ArrayList和LinkedList都实现了List接口,他们有以下的不同点:

  • ArrayList是基于索引的数据接口,它的底层是数组。它可以以O(1)时间复杂度对元素进行随机访问。与此对应,LinkedList是以元素列表的形式存储它的数据,每一个元素都和它的前一个和后一个元素链接在一起,在这种情况下,查找某个元素的时间复杂度是O(n)。

  • 相对于ArrayList,LinkedList的插入,添加,删除操作速度更快,因为当元素被添加到集合任意位置的时候,不需要像数组那样重新计算大小或者是更新索引。

  • LinkedList比ArrayList更占内存,因为LinkedList为每一个节点存储了两个引用,一个指向前一个元素,一个指向下一个元素。

也可以参考ArrayList vs. LinkedList

28.Comparable和Comparator接口是干什么的?列出它们的区别。

Java提供了只包含一个compareTo()方法的Comparable接口。这个方法可以个给两个对象排序。具体来说,它返回负数,0,正数来表明输入对象小于,等于,大于已经存在的对象。

Java提供了包含compare()和equals()两个方法的Comparator接口。compare()方法用来给两个输入参数排序,返回负数,0,正数表明第一个参数是小于,等于,大于第二个参数。equals()方法需要一个对象作为参数,它用来决定输入参数是否和comparator相等。只有当输入参数也是一个comparator并且输入参数和当前comparator的排序结果是相同的时候,这个方法才返回true。

29.什么是Java优先级队列(Priority Queue)?

PriorityQueue是一个基于优先级堆的无界队列,它的元素是按照自然顺序(natural order)排序的。在创建的时候,我们可以给它提供一个负责给元素排序的比较器。PriorityQueue不允许null值,因为他们没有自然顺序,或者说他们没有任何的相关联的比较器。最后,PriorityQueue不是线程安全的,入队和出队的时间复杂度是O(log(n))。

30.你了解大O符号(big-O notation)么?你能给出不同数据结构的例子么?

大O符号描述了当数据结构里面的元素增加的时候,算法的规模或者是性能在最坏的场景下有多么好。
大O符号也可用来描述其他的行为,比如:内存消耗。因为集合类实际上是数据结构,我们一般使用大O符号基于时间,内存和性能来选择最好的实现。大O符号可以对大量数据的性能给出一个很好的说明。

31.如何权衡是使用无序的数组还是有序的数组?

有序数组最大的好处在于查找的时间复杂度是O(log n),而无序数组是O(n)。有序数组的缺点是插入操作的时间复杂度是O(n),因为值大的元素需要往后移动来给新元素腾位置。相反,无序数组的插入时间复杂度是常量O(1)。

32.Java集合类框架的最佳实践有哪些?

  • 根据应用的需要正确选择要使用的集合的类型对性能非常重要,比如:假如元素的大小是固定的,而且能事先知道,我们就应该用Array而不是ArrayList。
  • 有些集合类允许指定初始容量。因此,如果我们能估计出存储的元素的数目,我们可以设置初始容量来避免重新计算hash值或者是扩容。
  • 为了类型安全,可读性和健壮性的原因总是要使用泛型。同时,使用泛型还可以避免运行时的ClassCastException。
  • 使用JDK提供的不变类(immutable class)作为Map的键可以避免为我们自己的类实现hashCode()和equals()方法。
  • 编程的时候接口优于实现。
  • 底层的集合实际上是空的情况下,返回长度是0的集合或者是数组,不要返回null。

33.Enumeration接口和Iterator接口的区别有哪些?

Enumeration速度是Iterator的2倍,同时占用更少的内存。但是,Iterator远远比Enumeration安全,因为其他线程不能够修改正在被iterator遍历的集合里面的对象。同时,Iterator允许调用者删除底层集合里面的元素,这对Enumeration来说是不可能的。

34.HashSet和TreeSet有什么区别?

HashSet是由一个hash表来实现的,因此,它的元素是无序的。add(),remove(),contains()方法的时间复杂度是O(1)。

另一方面,TreeSet是由一个树形的结构来实现的,它里面的元素是有序的。因此,add(),remove(),contains()方法的时间复杂度是O(logn)。

垃圾收集器(Garbage Collectors)

35.Java中垃圾回收有什么目的?什么时候进行垃圾回收?

垃圾回收的目的是识别并且丢弃应用不再使用的对象来释放和重用资源。

36.System.gc()和Runtime.gc()会做什么事情?

这两个方法用来提示JVM要进行垃圾回收。但是,立即开始还是延迟进行垃圾回收是取决于JVM的。

37.finalize()方法什么时候被调用?析构函数(finalization)的目的是什么?

在释放对象占用的内存之前,垃圾收集器会调用对象的finalize()方法。一般建议在该方法中释放对象持有的资源。

38.如果对象的引用被置为null,垃圾收集器是否会立即释放对象占用的内存?

不会,在下一个垃圾回收周期中,这个对象将是可被回收的。

39.Java堆的结构是什么样子的?什么是堆中的永久代(Perm Gen space)?

JVM的堆是运行时数据区,所有类的实例和数组都是在堆上分配内存。它在JVM启动的时候被创建。对象所占的堆内存是由自动内存管理系统也就是垃圾收集器回收。

堆内存是由存活和死亡的对象组成的。存活的对象是应用可以访问的,不会被垃圾回收。死亡的对象是应用不可访问尚且还没有被垃圾收集器回收掉的对象。一直到垃圾收集器把这些对象回收掉之前,他们会一直占据堆内存空间。

40.串行(serial)收集器和吞吐量(throughput)收集器的区别是什么?

吞吐量收集器使用并行版本的新生代垃圾收集器,它用于中等规模和大规模数据的应用程序。而串行收集器对大多数的小应用(在现代处理器上需要大概100M左右的内存)就足够了。

41.在Java中,对象什么时候可以被垃圾回收?

当对象对当前使用这个对象的应用程序变得不可触及的时候,这个对象就可以被回收了。

42.JVM的永久代中会发生垃圾回收么?

垃圾回收不会发生在永久代,如果永久代满了或者是超过了临界值,会触发完全垃圾回收(Full GC)。如果你仔细查看垃圾收集器的输出信息,就会发现永久代也是被回收的。这就是为什么正确的永久代大小对避免Full GC是非常重要的原因。

 

 

http://www.importnew.com/10980.html

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326703664&siteId=291194637