150个Java面试问答-最终清单(PDF下载)

150个Java面试问答-最终清单(PDF下载)_第1张图片

我们的Java面试问题和答案集合全都涉及可以在Java面试中使用的不同类型的问题,以使雇主可以测试您在Java和面向对象编程方面的技能。

在以下各节中,我们将讨论有关面向对象编程及其特性的Java面试问题,有关Java及其功能的一般问题,Java中的集合,垃圾收集器,异常处理,Java小程序,Swing,JDBC,远程方法调用(RMI) ,Servlet和JSP。

我们走吧…!

目录

面向对象编程(OOP) B.关于Java的一般问题 C.Java线程 D.Java集合 E.垃圾收集器 F.异常处理 G.Java小程序 Swing JDBC J.远程方法调用(RMI) Servlet JSP

A.面向对象编程(OOP)

1.什么是Java?

Java是一种并发,基于类和面向对象的计算机编程语言。 面向对象软件开发的优势如下所示:

  • 代码的模块化开发,使维护和修改变得容易。
  • 代码的可重用性。
  • 提高了代码的可靠性和灵活性。
  • 增加了对代码的理解。

2. OOP的概念是什么?

面向对象编程(OOP)包括:

  • 抽象化
  • 封装形式
  • 多态性
  • 遗产
  • 预定义类型必须是对象
  • 用户定义的类型必须是对象
  • 必须通过向对象发送消息来执行操作

3.提及Java的某些功能

在Java的普及中起重要作用的一些功能如下:

  • 面向对象
  • 平台无关
  • 高性能
  • 多线程
  • 随身携带
  • 安全

Java中的Helloworld的示例代码如下所示:

你好,世界

public class Helloworld{
    
public static void main(String args[])
{  
    System.out.println("Hello World");  
}  
    
}

4. Java 100%是面向对象的吗?

不是100%。 Java不能满足所有的OOP条件(预定义类型必须是对象),因为它使用了不是对象的八种原始数据类型(布尔,字节,字符,整数,浮点,双精度,长,短)。

5.什么是抽象?

抽象是将思想与特定实例分离开来的过程,因此根据其自身的功能而不是其实现细节来开发类。 Java支持公开接口的抽象类的创建和存在,而不包括所有方法的实际实现。 抽象技术旨在将类的实现细节与其行为分开。

下面介绍了抽象类Person。 它具有抽象方法getName。

抽象类人

public abstract class Person  
{  
    public abstract String getName(); 
}

Employee类扩展了Abstract类Person。 方法getName返回雇员的name属性。

员工阶层

public class Employee extends Person   
{  
    private String name;
    
    public Employee(String name)
    {
      this.name = name;
    }
    public String getName()
    {
       return this.name;
    }
    public static void main (String args[])  
    {  
        Employee employee = new Employee("John Wilson");
        
        System.out.println("Employee's Name "+ employee.getName()); 
        
        Person person = new Employee("Thomas Smith");
        
        System.out.println("Employee-Person's Name "+ person.getName());
        
        
    }  
}

6.什么是封装?

封装使对象能够隐藏其内部特征和行为。 每个对象提供许多方法,其他对象可以访问这些方法并更改其内部数据。 在Java中,有三种访问修饰符:public,private和protected。 每个修饰符都对相同或外部软件包中的其他类施加不同的访问权限。 下面列出了使用封装的一些优点:

  • 隐藏每个对象的属性可以保护每个对象的内部状态。
  • 因为可以独立更改或扩展对象的行为,所以它增加了代码的可用性和维护。
  • 它通过防止对象以不希望的方式相互交互来提高模块化。

您可以在此处参考我们的教程,以获取有关封装的更多详细信息和示例。

带有属性Id和Name的样本类Student被显示为封装示例。

学生班

public class Student{  
 private int id;  
 private String name;  
  
 public void setId(int id)
 {
   this.id = id;
 }
 
 public void setName(String name)
 {
   this.name = name;
 }
 
 public int getId()
 {
   return this.id;
 }
 
 public String getName()
 {
   return this.name;
 }
  
public static void main(String args[])
{  
  Student student=new Student();  
  student.setId(1034);
  student.setName("David Smith");

  System.out.println("Student id "+ student.getId());
  System.out.println("Student name "+ student.getName());
    
}  

}

7.抽象和封装之间有什么区别?

抽象和封装是互补的概念。 一方面,抽象集中于对象的行为。 另一方面,封装着重于对象行为的实现。 封装通常是通过隐藏有关对象内部状态的信息来实现的,因此可以看作是用于提供抽象的策略。

8.什么是多态?

多态是编程语言为不同的基础数据类型提供相同接口的能力。 多态类型是一种类型,其操作也可以应用于其他类型的值。

您可以在下面的示例中看到“车辆”界面具有方法“ invokeVelocity”。 卡车,火车和飞机实现了车辆界面,并且该方法将速度增加到与车辆类型相关的适当速度。

150个Java面试问答-最终清单(PDF下载)_第2张图片 多态性

9.多态性有哪些类型?

Java中有两种类型的多态性:

  • 编译时多态(静态绑定)–方法重载
  • 运行时多态(动态绑定)–方法覆盖

我们可以通过方法重载和方法重载来执行多态。

编译时间 运行
类的方法具有相同的名称。 每种方法都有不同数量的参数。 它可以具有不同类型和顺序的参数。 子类具有名称与超类方法相同的方法。 它具有超类方法的参数数量,参数类型和返回类型。
方法重载是要增加方法的行为。 它可以扩展到方法的行为。 方法重写是修改方法的行为。
重载的方法将没有相同的签名。 重写的方法将具有完全相同的签名。
在这种情况下,不需要继承。 继承是必需的。

计算器类的重载方法减去的示例代码如下所示:

计算器类

public class Calculator {

public int subtract(int a, int b)
{
   return a-b;
}
public double subtract( double a, double b)
{
 return a-b;
}

public static void main(String args[])
{
  Calculator calculator = new Calculator();
  System.out.println("Difference of 150 and 12 is " +calculator.subtract(150,12));
  System.out.println("Difference of 15.5 and 15.4 is " +calculator.subtract(15.50,15.40));
}}

方法覆盖在Shape类中显示。 Shape有一个方法getArea。

形状等级

public class Shape
{  
  public void getArea(){System.out.println("Shape Area");}  
}

Rectangle类重写getArea方法,并且该方法的实现特定于Rectangle。 覆盖注释用于向编译器指示该方法被覆盖。 使用注释可以提高代码的可读性。

矩形类

public class Rectangle extends Shape{ 
  
  @Override
  public void getArea()
  {
    System.out.println("Rectangle Area");
  
  }  
  
  

  public static void main(String args[])
  {  
    Shape shape = new Shape();
    
    shape.getArea();
    
    Rectangle rectangle = new Rectangle();  
    
    rectangle.getArea();  
  }  
}

10.什么是继承?

继承为对象提供了获取另一个类(称为基类)的字段和方法的能力。 继承提供了代码的可重用性,并且可以用于继承现有类,而无需对其进行修改。

下面显示的示例类Mammal具有一个构造函数。

哺乳动物类

public class Mammal{  

 public Mammal()
 {
   System.out.println("Mammal created"); 
 }
 
}

Man类扩展了具有默认构造函数的Mammal。 示例代码如下所示。

男子班

public class Man extends Mammal{ 

 public Man()
 {  
   System.out.println("Man is created");  
 }  
}

通过使用默认构造函数创建Man的实例来测试继承。 示例代码显示为演示继承。

TestInheritance类

public class TestInheritance{

public static void main(String args[])
{  
   Man man = new Man();  
 }  
}

11.什么是成分?

除了“部分”的生命周期由“整体”控制之外, 组成与“聚集”完全相同。 此控件可以是直接的或传递的。 也就是说,“整个”可能直接负责创建或销毁“零件”,或者可以接受已经创建的零件,然后将其传递给承担此责任的其他整体。

下图显示了“汽车”示例类,以演示轮胎,门,窗和转向的组成。

车类

public class Car 
{  
  private Tire[] tires;
  
  private Door[] doors;
  
  private Steering steering;
  
  private Window[] windows;
}

class Tire
{
    
}
  
class Door
{
    
}

class Steering
{
    
}

class Window
{
    
}

12.什么是协会?

关联表示一个实例向另一个实例发送消息的能力。 尽管通常也可以将其实现为方法自变量或创建局部变量,但通常使用指针或引用实例变量来实现。

13.什么是聚合?

聚集是典型的整体/部分关系。 这与关联完全相同,但实例不能具有循环聚合关系。

下面显示了示例类Person,以演示与Address的聚合关系。

人类

public class Person
{  
  private Address address;

}

class Address
{
  private String city;
  
  private String state;
  
  private String country;
  
  private String line1;
  
  private String line2;

}

B.关于Java的一般问题

14.什么是JVM?

Java虚拟机(JVM)是​​可以执行Java 字节码的进程虚拟机 。 每个Java源文件都被编译为字节码文件,该文件由JVM执行。

15. Java为什么称为平台独立编程语言?

Java旨在允许构建可以在任何平台上运行的应用程序,而不必由程序员针对每个单独的平台进行重写或重新编译。 Java虚拟机使之成为可能,因为它知道特定的指令长度和底层硬件平台的其他特殊性。

16. JDK和JRE有什么区别?

Java运行时环境(JRE)基本上是执行Java程序的Java虚拟机(JVM)。 它还包括用于执行applet的浏览器插件。 Java开发工具包(JDK)是用于Java的功能齐全的软件开发工具包,包括JRE,编译器和工具(如JavaDoc和Java Debugger ),以便用户开发,编译和执行Java应用程序。

JDK 杰瑞
JDK代表术语:Java开发工具包。 JRE代表术语:Java运行时环境。
JDK是用于编译,记录和打包Java软件的工具。 JRE是运行时环境。 JavaByte代码在环境中执行。
JDK具有JRE和开发工具。 JRE是JVM实现

17. static关键字是什么意思?

static关键字表示可以访问成员变量或方法,而无需实例化其所属的类。

静态方法示例如下所示:

静态方法

static void printGreeting()  
    {
    
    
    }

18.您可以在Java中覆盖私有方法还是静态方法?

用户无法覆盖Java中的静态方法 ,因为方法覆盖基于运行时的动态绑定,而静态方法是在编译时静态绑定的。 静态方法未与类的任何实例相关联,因此该概念不适用。

19.您可以在静态上下文中访问非静态变量吗?

Java中的静态变量属于其类,并且其所有实例的值都相同。 JVM加载类时,将初始化静态变量。 如果您的代码试图在没有任何实例的情况下访问非静态变量,则编译器会抱怨,因为这些变量尚未创建并且它们与任何实例都没有关联。

20. Java支持哪些数据类型?

Java编程语言支持的八种原始数据类型是:

  • 字节
  • 整型
  • 浮动
  • 布尔值
  • 烧焦

21.什么是自动装箱和拆箱?

自动装箱是Java编译器在原始类型及其对应的对象包装器类之间进行的自动转换 。 例如,编译器将int转换为Integer ,将double转换为Double ,依此类推。 如果转换为其他方式,则此操作称为拆箱。

22.什么是Java中的函数覆盖和重载?

当同一类中的两个或多个方法具有完全相同的名称,但参数不同时,就会发生Java中的方法重载。 另一方面,方法覆盖定义为子类重新定义与父类相同的方法时的情况。 重写的方法必须具有相同的名称,参数列表和返回类型。 覆盖方法可能不会限制对其覆盖的方法的访问。

23.什么是构造函数?

创建新对象时,将调用构造函数。 每个类都有一个构造函数 。 如果程序员没有为类提供构造函数,则Java编译器(Javac)为该类创建一个默认构造函数。

下例显示了Java中的默认构造函数:

默认构造函数

public Man()
 {  
   System.out.println("Man is created");  
 }

以下示例显示了采用参数的构造函数:

建设者

private String name;
    
    public Employee(String name)
    {
      this.name = name;
    }

24.什么是构造函数重载?

构造函数重载类似于Java中的方法重载。 可以为单个类创建不同的构造函数。 每个构造函数必须具有自己的唯一参数列表。

25.什么是复制构造函数?

最后,Java确实支持像C ++这样的副本构造函数,但是不同之处在于,如果您不编写自己的副本,则Java不会创建默认的副本构造函数。

Employee类的复制构造函数如下所示:

复制构造函数

public class Employee extends Person   
{  
    private String name;
    
    public Employee(String name)
    {
      this.name = name;
    }
    
    public Employee(Employee emp)
    {
      this.name = emp.name;
    }
    
}

26. Java是否支持多重继承?

不,Java不支持多重继承。 每个类只能在一个类上扩展,但可以实现多个接口。

150个Java面试问答-最终清单(PDF下载)_第3张图片 多重继承

27.接口和抽象类有什么区别?

Java提供并支持抽象类和接口的创建。 两种实现都有一些共同的特征,但是它们在以下特征上有所不同:

  • 接口中的所有方法都是隐式抽象的。 另一方面,抽象类可能同时包含抽象方法和非抽象方法。
  • 一个类可以实现许多接口,但只能扩展一个抽象类。
  • 为了使类实现接口,它必须实现其所有声明的方法。 但是,一个类可能无法实现抽象类的所有已声明方法。 但是,在这种情况下,子类也必须声明为抽象。
  • 抽象类可以实现接口,甚至不提供接口方法的实现。
  • 在Java接口中声明的变量默认为final。 抽象类可能包含非最终变量。
  • 默认情况下,Java接口的成员是公共的。 抽象类的成员可以是私有的,受保护的或公共的。
  • 接口绝对是抽象的,无法实例化。 如果抽象类包含main方法,则它也不能实例化,但可以被调用。

另外,请查看JDK 8的Abstract类和接口的区别 。

接口 抽象类
接口具有方法签名。 它没有任何实现。 抽象类具有要覆盖的抽象方法和细节。
一个类可以实现多个接口 在这种情况下,一个类只能扩展一个抽象类
接口具有所有抽象方法。 非抽象方法可以存在于抽象类中。
接口中不能存在实例属性。 实例属性可以存在于抽象类中。
接口是公开可见的还是不可见的。 抽象类可以是公共的,私有的和受保护的可见性。
接口中的任何更改都会影响实现该接口的类。 将方法添加到抽象类并实现它不需要更改派生类的代码。
接口不能具有构造函数 抽象类可以具有构造函数
接口在性能方面很慢 抽象类可以快速执行派生类中的方法。

28.什么是参考传递和价值传递?

通过值传递对象时,这意味着传递对象的副本。 因此,即使对该对象进行了更改,它也不会影响原始值。 通过引用传递对象时,这意味着不传递实际对象,而是传递该对象的引用。 因此,外部方法所做的任何更改也都会反映在所有地方。

下面提供了示例代码,其中显示了按值传递。

价值传递

public class ComputingEngine 
{ 
    public static void main(String[] args) 
    { 
        int x = 15;
        ComputingEngine engine = new ComputingEngine();
        engine.modify(x); 
        System.out.println("The value of x after passing by value "+x); 
    } 
    public  void modify(int x) 
    { 
        x = 12; 
    } 
}

下面的示例显示了代码中的引用传递。

通过参考

public class ComputingEngine 
{ 
    public static void main(String[] args) 
    { 
        
        ComputingEngine engine = new ComputingEngine();
        
       
        Computation computation = new Computation(65);
        engine.changeComputedValue(computation);
        
        System.out.println("The value of x after passing by reference "+ computation.x);
        
    } 
    
  
    
    public void changeComputedValue(Computation computation)
    {
        computation = new Computation();
        computation.x = 40;
    }
}


class Computation 
{ 
    int x; 
    Computation(int i) { x = i; } 
    Computation()      { x = 1; } 
}

29.易变变量的目的是什么?

易失性变量的值可以通过不同的线程进行修改。 他们将永远没有机会阻止并保持锁。 只要访问变量,就会发生同步。 使用volatile可能比使用锁快,但在某些情况下将不起作用。 Java 5扩展了volatile有效的情况范围; 特别是,双重检查锁定现在可以正常工作。

volatile变量的示例代码如下所示:

挥发性变量

public class DistributedObject {

    public volatile int count = 0;

}

30.瞬时变量的目的是什么?

即使将瞬态变量所属的类进行了序列化,也不会对其进行序列化。

具有瞬态变量的示例类如下所示:

暂时变量

public class Paper implements Serializable
{
    private int id;
    private String title;
    private String author;
    private transient int version = 1;
    
}

31.什么是局部变量和实例变量?

局部变量 实例变量
局部变量在方法或构造函数中声明。 可以在一个块中声明 实例变量在类内声明。
使用前需要初始化局部变量。 该代码将无法编译。
实例变量初始化不是必需的。 如果未初始化,则使用默认值。

32. Java中有哪些不同的访问修饰符?

有四种类型的访问修饰符:

  • 公开-可从应用程序中的任何地方访问
  • 受保护–可在包中以及任何包中的子类中访问
  • 包私有(默认)–只能在包内访问
  • 私有–仅在声明它的同一个类中可以访问

33.静态绑定和动态绑定之间的区别

静态绑定 动态绑定
过程的定义与静态绑定有关 动态绑定的一个示例是过程的激活
声明变量名称是为了静态绑定变量。 名称的绑定可以是动态绑定。
声明的范围是静态绑定的。 绑定的生命周期是动态绑定的。

静态绑定的示例代码如下所示:

静态绑定

public class Shape
{  
  public void getArea()
   {
     System.out.println("Shape Area");
    }  


public static void main(String args[])
  {  
    Shape shape = new Shape();
    
    shape.getArea();
  }
}

动态绑定的示例代码如下所示:

动态绑定

public class Rectangle extends Shape{ 
  
  
  public void getArea()
  {
    System.out.println("Rectangle Area");
  
  }  
  
  
  
  public static void main(String args[])
  {  
  
    Shape shape = new Rectangle();  
    
    shape.getArea();  
  }  
}

34.什么是包装器类?

包装器类将Java原语转换为对象。 因此,原始包装器类是一个包装器类,它包装,隐藏或包装来自八个原始数据类型的数据类型,以便可以使用它们在另一个类或其他类中的方法来创建实例化的对象。 原始包装器类可在Java API中找到。

35.什么是单身人士课,我们如何使单身人士课?

在单例课程中,我们:

  • 确保仅存在单例类的一个实例
  • 提供对该实例的全局访问

要创建单例类,我们:

  • 将该类的所有构造函数声明为私有
  • 提供一个静态方法,该方法返回对该实例的引用

下面的代码示例显示了Double Checked Singleton类的实现。

单身人士班

public class DoubleCheckedSingleton {
    private static volatile DoubleCheckedSingleton instance;
    public static DoubleCheckedSingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckedSingleton .class) {
                if (instance == null) {
                    instance = new DoubleCheckedSingleton();
                }
            }
        }
        return instance;
    }
 
}

C.Java线程

36.进程和线程之间有什么区别?

进程是程序的执行,而线程是进程内的单个执行序列。 一个进程可以包含多个线程。 线程有时称为轻量级进程。

Craft.io流程 线程数
过程与程序的执行有关。 进程由多个线程组成。
进程之间使用进程间通信进行通信。 进程的线程可以相互通信。
流程可以控制子流程。 进程的线程可以控制其他线程。
父进程中的任何修改都不会更改子进程 主线程中的任何修改都可能影响进程中其他线程的行为。
进程在单独的内存空间中执行。 线程在共享内存空间中执行。
操作系统控制过程。 软件开发人员可以控制线程的使用。
流程彼此独立。 线程彼此依赖。

您想要哪一个,为什么?

可以使用三种方法来创建线程:

  • 一个类可以扩展Thread类。
  • 一个类可以实现Runnable接口。
  • 应用程序可以使用Executor框架来创建线程池。

首选Runnable接口,因为它不需要对象来继承Thread类。 如果您的应用程序设计需要多重继承,则只有接口可以为您提供帮助。 而且,线程池非常有效,可以非常容易地实现和使用。

38.从高层次解释可用线程状态。

在执行期间,线程可以处于以下状态之一 :

  • NEW :线程准备就绪,可以运行,但不一定立即开始运行。
  • RUNNABLE :Java虚拟机(JVM)正在主动执行线程的代码。
  • BLOCKED :线程处于阻塞状态,同时等待监视器锁。
  • 等待 :线程等待另一个线程执行特定操作。
  • TIMED_WAITING :线程等待另一个线程执行特定操作,直到指定的等待时间。
  • 终止 :线程已完成执行。

39.同步的方法和块之间有什么区别?

在Java编程中,每个对象都有一个锁。 线程可以通过使用synced关键字来获取对象的锁。 可以在方法级别(粗粒度锁定)或代码块级别(细粒度锁定)中应用synced关键字。

40.监视器内部如何进行线程同步?

JVM将锁与监视器结合使用。 监视器基本上是监视一系列同步代码并确保一次仅一个线程执行同步代码段的监护人。 每个监视器都与一个对象引用关联。 线程获得锁之前,不允许执行代码。

41.什么是僵局?

在继续进行之前, 两个进程互相等待完成的情况 。 结果是两个进程都无限等待。

42.如何确保N个线程可以无死锁地访问N个资源?

在使用N个线程时避免死锁的一种非常简单的方法是在锁上施加一个顺序,并强制每个线程遵循该顺序。 因此,如果所有线程以相同顺序锁定和解锁互斥锁,则不会出现死锁。

43. Java中的wait和sleep方法有什么区别?

等待 睡觉
呼吁 当对象上有调用时,当前线程在锁对象上同步。 线程调用发生在当前正在执行的线程上。
已同步 同步用于从多个线程访问同一对象。 同步用于在多个线程的睡眠线程上进行睡眠。
保持锁 释放其他对象的锁,以便有机会执行 如果指定了超时或有人中断,请保持锁定至少t次。
唤醒条件 直到调用notify(),然后从对象调用notifyAll() 直到至少时间到期或调用interrupt()。
用法 用于时间同步 用于多线程同步

D.Java集合

44. Java Collections Framework的基本接口是什么?

Java Collections Framework提供了一组精心设计的接口和类,这些接口和类支持对对象集合的操作。 Java Collections Framework中最基本的接口是:

  • Collection ,代表一组称为其元素的对象。
  • Set ,这是一个不能包含重复元素的集合。
  • List ,这是一个有序集合,可以包含重复元素。
  • Map ,这是一个将键映射到值并且不能包含重复键的对象。
150个Java面试问答-最终清单(PDF下载)_第4张图片 集合层次结构

45.为什么Collection不扩展Cloneable和Serializable接口?

Collection接口指定称为元素的对象组。 Collection的每个具体实现都可以选择自己的方式来维护和排序其元素。 一些集合允许重复的键,而另一些集合则不允许。 在处理实际的实现时,克隆或序列化的语义和含义都会发挥作用。 因此,集合的具体实现应决定如何克隆或序列化它们。

46.什么是迭代器?

Iterator接口提供了许多可以迭代任何Collection的方法 。 每个Java集合都包含返回Iterator实例的iterator方法。 迭代器能够在迭代过程中从基础集合中删除元素 。

47. Iterator和ListIterator有什么区别?

这些元素的区别如下:

  • 迭代器可用于遍历Set和List集合,而ListIterator只能用于遍历List。
  • 迭代器只能在向前的方向上遍历一个集合,而ListIterator可以在两个方向上遍历一个List。
  • ListIterator实现Iterator接口,并包含其他功能,例如添加元素,替换元素,获取上一个和下一个元素的索引位置等。

48.故障快速和故障安全之间有什么区别?

Iterator的故障安全属性可与基础集合的克隆一起使用,因此,不受集合中任何修改的影响。 java.util包中的所有收集类都是快速失败的,而java.util.concurrent中的收集类则是故障安全的。 快速故障迭代器抛出ConcurrentModificationException ,而故障安全迭代器从不抛出此类异常。

49. HashMap如何在Java中工作?

Java中的HashMap存储键值对 。 HashMap需要一个哈希函数,并使用hashCode和equals方法,以便分别将元素放置到集合中或从集合中检索元素。 调用put方法时,HashMap将计算键的哈希值,并将该对存储在集合内的适当索引中。 如果键存在,则其值将用新值更新。 HashMap的一些重要特征是其容量,负载因子和调整阈值的大小。

50. hashCode()和equals()方法的重要性是什么?

在Java中, HashMap使用hashCode和equals方法确定键值对的索引并检测重复项。 更具体地说,使用hashCode方法来确定指定密钥的存储位置。 由于不同的键可能会产生相同的哈希值,因此使用equals方法来确定指定键在集合中是否实际存在。 因此,两种方法的实现对于HashMap的准确性和效率至关重要。

51. HashMap和Hashtable有什么区别?

HashMap和Hashtable类都实现Map接口,因此具有非常相似的特性。 但是,它们在以下功能方面有所不同:

  • HashMap允许存在空键和值,而Hashtable既不允许空键也不允许空值。
  • Hashtable是同步的,而HashMap不是同步的。 因此,在单线程环境中首选使用HashMap,而在多线程环境中使用Hashtable。
  • HashMap提供其键集,Java应用程序可以对其进行迭代。 因此,HashMap是快速失败的。 另一方面,哈希表提供其键的枚举 。
  • Hashtable类被认为是旧类。

什么时候在ArrayList上使用Array?

Array和ArrayList类在以下功能上有所不同:

  • 数组可以包含原语或对象,而ArrayList只能包含对象。
  • 数组具有固定大小,而ArrayList是动态的。
  • ArrayList提供更多的方法和功能,例如addAll , removeAll , iterator等等。
  • 对于原始数据类型的列表,集合使用自动装箱来减少编码工作。 但是,这种方法使它们在处理固定大小的原始数据类型时速度较慢。
数组 数组列表
数组不应具有不同数据类型的值 数组列表可以具有不同数据类型的值。
声明时定义了错误的大小 ArrayList的大小可以动态更改
您必须指定索引才能在数组中添加数据 您不需要在ArrayList中指定索引
数组未参数化类型 可以对数组列表进行参数化。
数组可以具有原始数据类型以及对象 数组列表只能有对象,不允许使用原始数据类型

53. ArrayList和LinkedList有什么区别?

ArrayList和LinkedList类都实现List接口,但是它们在以下功能上有所不同:

  • ArrayList是由Array支持的基于索引的数据结构。 它提供对元素的随机访问,其性能等于O(1)。 另一方面,LinkedList将其数据存储为元素列表,并且每个元素都链接到其上一个和下一个元素。 在这种情况下,元素的搜索操作的执行时间等于O(n)。
  • 与ArrayList相比,LinkedList中元素的插入,添加和删除操作更快,因为在集合中任意位置添加元素时,无需调整数组大小或更新索引。
  • LinkedList比ArrayList消耗更多的内存,因为LinkedList中的每个节点都存储两个引用,一个引用用于其上一个元素,一个用于其下一个元素。

另请参阅我们的文章ArrayList与LinkedList 。

54.比较器和比较器有什么区别?

  • Java提供了Comparable接口,该接口仅包含一种称为compareTo的方法。 此方法比较两个对象,以便在它们之间施加一个顺序。 具体来说,它返回负整数,零或正整数,以指示输入对象小于,等于或大于现有对象。
  • Java提供了Comparator接口,其中包含两个方法,称为compare和equals 。 第一种方法比较其两个输入参数,并在它们之间施加一个顺序。 它返回负整数,零或正整数,以指示第一个参数小于,等于或大于第二个参数。 第二种方法需要一个对象作为参数,目的是确定输入对象是否等于比较器。 仅当指定的对象也是比较器并且施加与该比较器相同的顺序时,该方法才返回true。

55.什么是Java优先级队列?

PriorityQueue是一个无限制队列,基于优先级堆,并且其元素以其自然顺序排序。 在创建它的时候,我们可以提供一个Comparator,它负责对PriorityQueue的元素进行排序。 PriorityQueue不允许null值 ,那些不提供自然顺序的对象或那些没有任何与之关联的比较器的对象。 最后,Java PriorityQueue不是线程安全的,并且其入队和出队操作需要O(log(n))时间。

56.您对big-O表示法了解多少,并且可以举出一些有关不同数据结构的示例吗?

Big-O符号只是描述了在数据结构中元素数量增加时,算法在最坏情况下的伸缩性或性能。 Big-O表示法还可用于描述其他行为,例如内存消耗。 由于收集类实际上是数据结构,因此我们通常使用Big-O表示法,根据时间,内存和性能来选择要使用的最佳实现。 Big-O表示法可以很好地说明大量数据的性能。

57.使用无序数组与有序数组之间的权衡是什么?

有序数组的主要优点是,与无序数组的时间复杂度为O(n)相比,搜索时间的时间复杂度为O(log n)。 有序数组的缺点是插入操作的时间复杂度为O(n),因为必须移动具有较高值的​​元素才能为新元素腾出空间。 取而代之的是,对无序数组的插入操作将花费O(1)的恒定时间。

58.与Java Collection框架相关的一些最佳实践是什么?

  • Choosing the right type of the collection to use, based on the application's needs, is very crucial for its performance. For example if the size of the elements is fixed and know a priori, we shall use an Array , instead of an ArrayList .
  • Some collection classes allow us to specify their initial capacity. Thus, if we have an estimation on the number of elements that will be stored, we can use it to avoid rehashing or resizing.
  • Always use Generics for type-safety, readability, and robustness. Also, by using Generics you avoid the ClassCastException during runtime.
  • Use immutable classes provided by the Java Development Kit (JDK) as a key in a Map, in order to avoid the implementation of the hashCode and equals methods for our custom class.
  • Program in terms of interface not implementation.
  • Return zero-length collections or arrays as opposed to returning a null in case the underlying collection is actually empty.

59. What is the difference between Enumeration and Iterator interfaces?

Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object that is currently traversed by the iterator. Also, Iterators allow the caller to remove elements from the underlying collection, something which is not possible with Enumerations.

60. What is the difference between HashSet and TreeSet?

The HashSet is Implemented using a hash table and thus, its elements are not ordered. The add, remove, and contains methods of a HashSet have constant time complexity O(1). On the other hand, a TreeSet is implemented using a tree structure. The elements in a TreeSet are sorted, and thus, the add, remove, and contains methods have time complexity of O(logn).

E.Garbage Collectors

61. What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application, in order for the resources to be reclaimed and reused.

62. What does System.gc() and Runtime.gc() methods do?

These methods can be used as a hint to the JVM, in order to start a garbage collection. However, this it is up to the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time.

Sample class ReferenceObject is shown below to demonstrate the usage of System.gc and Runtime.gc methods.

public class ReferenceObject
{  
 public void finalize()
 {
    System.out.println("object is garbage collected");
    
 }

 public static void main(String args[]){  
  ReferenceObject refObj1=new ReferenceObject();  
  ReferenceObject refObj2=new ReferenceObject();  
  refObj1=null;  
  refObj2=null;  
  System.gc(); 

  Runtime.gc(); 
 }  
}

63. When is the finalize() called? What is the purpose of finalization?

The finalize method is called by the garbage collector, just before releasing the object's memory. It is normally advised to release resources held by the object inside the finalize method.

Finalize method in ReferenceObject class is shown below as an example.

Finalize Method

public class ReferenceObject
{  
 public void finalize()
 {
    System.out.println("object is garbage collected");
    
 }
 }

64. If an object reference is set to null, will the Garbage Collector immediately free the memory held by that object?

No, the object will be available for garbage collection in the next cycle of the garbage collector.

65. What is structure of Java Heap?

The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.

66. What is the difference between Serial and Throughput Garbage collector?

The throughput garbage collector uses a parallel version of the young generation collector and is meant to be used with applications that have medium to large data sets. On the other hand, the serial collector is usually adequate for most small applications (those requiring heaps of up to approximately 100MB on modern processors).

67. When does an Object becomes eligible for Garbage collection in Java?

A Java object is subject to garbage collection when it becomes unreachable to the program in which it is currently used.

68. Does Garbage collection occur in permanent generation space in JVM?

Garbage Collection does occur in PermGen space and if PermGen space is full or cross a threshold, it can trigger a full garbage collection. If you look carefully at the output of the garbage collector, you will find that PermGen space is also garbage collected. This is the reason why correct sizing of PermGen space is important to avoid frequent full garbage collections. Also check our article Java 8: PermGen to Metaspace .

F.Exception Handling

69. What are the differences between Checked Exception and Unchecked Exception?

Checked Exception Unchecked Exception
known as compile time exceptions known as Runtime exceptions
propagated using throws keyword automatically propagated
can create custom exception by extending java.lang.Exception class can create custom exception by extending Runtime exception

70. What is the difference between Exception and Error in java?

Exception and Error classes are both subclasses of the Throwable class. The Exception class is used for exceptional conditions that a user's program should catch. The Error class defines exceptions that are not expected to be caught by the user program.

71. What is the difference between throw and throws?

The throw keyword is used to explicitly raise a exception within the program. On the contrary, the throws clause is used to indicate those exceptions that are not handled by a method. Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. Finally, multiple exceptions are separated by a comma.

Throw Throws
Throw is used for throwing an exception explicitly. To declar an exception,throws is used.
Using throw only, Checked exceptions can not be propagated. Using throws, Checked exception can be propagated.
Throw is always used with an instance. Throws is always used with a class.
Throw is used inside the method. Throws is used always with the method signature.
You should not throw multiple exception You can declare multiple exceptions.

72. What is the importance of finally block in exception handling?

A finally block will always be executed, whether or not an exception is actually thrown. Even in the case where the catch statement is missing and an exception is thrown, the finally block will still be executed. Last thing to mention is that the finally block is used to release resources like I/O buffers, database connections, etc.

Sample code below shows the finally block when exception is thrown.

Finally Block

public class DivideByZeroException
{  
     public static void main(String []args){  
        try{  
            int a = 1;   
            System.out.println(a/0);  
        }
        catch(Exception exception)
        {
          System.out.println("exception is thrown");
        }
        finally  
        {  
            System.out.println("after the exception is handled");  
        }  
     }  
}

73. What will happen to the Exception object after exception handling?

The Exception object will be garbage collected in the next garbage collection.

74. What purpose does the keywords final, finally, and finalize fulfill?

  • Final keyword is used to apply restrictions on class(immutable), method(cannot override) and variable(constant).
  • Finally is a block that always executes when the try block exits even if an unexpected exception occurs.
  • Finalize is a method called to clean or release the resources by the Garbage Collector before destroying the object.

G.Java Applets

75. What is an Applet?

A java applet is program that can be included in a HTML page and be executed in a java enabled client browser. Applets are used for creating dynamic and interactive web applications.

76. Explain the life cycle of an Applet.

An applet may undergo the following states:

  • Init : An applet is initialized each time is loaded.
  • Start : Begin the execution of an applet.
  • Stop : Stop the execution of an applet.
  • Destroy : Perform a final cleanup, before unloading the applet.
150个Java面试问答-最终清单(PDF下载)_第5张图片 Applet Lifecycle

77. What happens when an applet is loaded?

First of all, an instance of the applet's controlling class is created. Then, the applet initializes itself and finally, it starts running.

78. What is the difference between an Applet and a Java Application?

Applets are executed within a java enabled browser, but a Java application is a standalone Java program that can be executed outside of a browser. However, they both require the existence of a Java Virtual Machine (JVM). Furthermore, a Java application requires a main method with a specific signature, in order to start its execution. Java applets do not need such a method to start their execution. Finally, Java applets typically use a restrictive security policy, while Java applications usually use more relaxed security policies.

79. What are the restrictions imposed on Java applets?

Mostly due to security reasons, the following restrictions are imposed on Java applets:

  • An applet cannot load libraries or define native methods.
  • An applet cannot ordinarily read or write files on the execution host.
  • An applet cannot read certain system properties.
  • An applet cannot make network connections except to the host that it came from.
  • An applet cannot start any program on the host that is executing it.

80. What are untrusted applets?

Untrusted applets are those Java applets that cannot access or execute local system files. By default, all downloaded applets are considered as untrusted.

81. What is the difference between applets loaded over the internet and applets loaded via the file system?

Regarding the case where an applet is loaded over the internet, the applet is loaded by the applet classloader and is subject to the restrictions enforced by the applet security manager. Regarding the case where an applet is loaded from the client's local disk, the applet is loaded by the file system loader. Applets loaded via the file system are allowed to read files, write files and to load libraries on the client. Also, applets loaded via the file system are allowed to execute processes and finally, applets loaded via the file system are not passed through the byte code verifier.

82. What is the applet class loader, and what does it provide?

When an applet is loaded over the internet, the applet is loaded by the applet classloader. The class loader enforces the Java namespace hierarchy. Also, the class loader guarantees that a unique namespace exists for classes that come from the local file system, and that a unique namespace exists for each network source. When a browser loads an applet over the net, that applet's classes are placed in a private namespace associated with the applet's origin. Then, those classes loaded by the class loader are passed through the verifier. The verifier checks that the class file conforms to the Java language specification. Among other things, the verifier ensures that there are no stack overflows or underflows and that the parameters to all bytecode instructions are correct.

83. What is the applet security manager, and what does it provide?

The applet security manager is a mechanism to impose restrictions on Java applets. A browser may only have one security manager. The security manager is established at startup, and it cannot thereafter be replaced, overloaded, overridden, or extended.

H.Swing

84. What is the difference between a Choice and a List?

A Choice is displayed in a compact form that must be pulled down, in order for a user to be able to see the list of all available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

85. What is a layout manager?

A layout manager is the used to organize the components in a container.

86. What is the difference between a Scrollbar and a JScrollPane?

A Scrollbar is a Component , but not a Container . A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

87. Which Swing methods are thread-safe?

There are only three thread-safe methods: repaint, revalidate, and invalidate.

88. Name three Component subclasses that support painting.

The Canvas , Frame , Panel , and Applet classes support painting.

89. What is clipping?

Clipping is defined as the process of confining paint operations to a limited area or shape.

90. What is the difference between a MenuItem and a CheckboxMenuItem?

The CheckboxMenuItem class extends the MenuItem class and supports a menu item that may be either checked or unchecked.

91. How are the elements of a BorderLayout organized?

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

92. How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are organized according to a grid. The elements are of different sizes and may occupy more than one row or column of the grid. Thus, the rows and columns may have different sizes.

93. What is the difference between a Window and a Frame?

The Frame class extends the Window class and defines a main application window that can have a menu bar.

94. What is the relationship between clipping and repainting?

When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

95. What is the relationship between an event-listener interface and an event-adapter class?

An event-listener interface defines the methods that must be implemented by an event handler for a particular event. An event adapter provides a default implementation of an event-listener interface.

96. How can a GUI component handle its own events?

A GUI component can handle its own events, by implementing the corresponding event-listener interface and adding itself as its own event listener.

97. What advantage do Java's layout managers provide over traditional windowing systems?

Java uses layout managers to lay out components in a consistent manner, across all windowing platforms. Since layout managers are not tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.

98. What is the design pattern that Java uses for all Swing components?

The design pattern used by Java for all Swing components is the Model View Controller (MVC) pattern.

150个Java面试问答-最终清单(PDF下载)_第6张图片 MVC

I.JDBC

99. What is JDBC?

JDBC is an abstraction layer that allows users to choose between databases. JDBC enables developers to write database applications in Java , without having to concern themselves with the underlying details of a particular database.

100. What are the JDBC API components?

The java.sql package contains:

Interfaces :

  • 司机
  • 连接
  • 声明
  • PreparedStatement
  • CallableStatement
  • ResultSet

Classes :

  • DriverManager
  • SQLException

101. Explain the role of Driver in JDBC.

The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each driver must provide implementations for the following interfaces of the java.sql package: Connection , Statement , PreparedStatement , CallableStatement , ResultSet and Driver .

102. What is JDBC Connection interface?

Connection interface maintains a session with the database. SQL statements are executed and results are returned within the context of a connection. A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

103. What does Connection pooling mean?

The interaction with a database can be costly, regarding the opening and closing of database connections. Especially, when the number of database clients increases, this cost is very high and a large number of resources is consumed.A pool of database connections is obtained at start up by the application server and is maintained in a pool. A request for a connection is served by a connection residing in the pool . In the end of the connection, the request is returned to the pool and can be used to satisfy future requests.

104. What is the role of JDBC DriverManager class?

The DriverManager provides the user with a basic service for managing a set of JDBC drivers. It maintains contact with the available drivers and establishes a database connection with an appropriate one.

105. What is the purpose Class.forName method?

This method is used to load the driver that will establish a connection to the database.

Sample Class ClassLoader is shown below to demonstrate the usage of Class.forName() method.

Class.forName

public class ClassLoader 
{

   public static void main(String[] args) {

      try 
      {
         Class cls = Class.forName("BasicClass");
         
         .....
         
         System.out.println("Class = " + cls.getName());
         
      }
         
     catch(ClassNotFoundException exception) 
      {
         System.out.println(exception.toString());
      }
      
}

106. What is the advantage of PreparedStatement over Statement?

PreparedStatement is precompiled and thus, performance is much better . Also, PreparedStatement objects can be reused with different input values to their queries.

107. What is the use of CallableStatement?

A CallableStatement is used to execute stored procedures. Stored procedures are stored and offered by a database. Stored procedures may take input values from the user and may return a result. The usage of stored procedures is highly encouraged, because it offers security and modularity.The method that prepares a CallableStatement is CallableStatement.prepareCall().

108. What do you mean by batch processing in JDBC?

Batch processing groups related SQL statements and execute multiple queries when the batch size reaches a desired threshold. This makes the performance faster.

J.Remote Method Invocation (RMI)

109. What is RMI?

The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and distributed garbage collection. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object. Check some RMI Tips here .

110. What is the basic principle of RMI architecture?

The RMI architecture is based on a very important principle which states that the definition of the behavior and the implementation of that behavior, are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs.

150个Java面试问答-最终清单(PDF下载)_第7张图片 RMI Architecture

111. What are the layers of RMI Architecture?

The RMI architecture consists of the following layers:

  • Stub and Skeleton layer : This layer lies just beneath the view of the developer. This layer is responsible for intercepting method calls made by the client to the interface and redirect these calls to a remote RMI Service.
  • Remote Reference Layer : The second layer of the RMI architecture deals with the interpretation of references made from the client to the server's remote objects. This layer interprets and manages references made from clients to the remote service objects. The connection is a one-to-one (unicast) link.
  • Transport layer : This layer is responsible for connecting the two JVM participating in the service. This layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

112. What is the role of Remote Interface in RMI?

The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. A class that implements a remote interface should declare the remote interfaces being implemented, define the constructor for each remote object and provide an implementation for each remote method in all remote interfaces.

113. What is the role of the java.rmi.Naming Class?

The java.rmi.Naming class provides methods for storing and obtaining references to remote objects in the remote object registry. Each method of the Naming class takes as one of its arguments a name that is a String in URL format.

114. What is meant by binding in RMI?

Binding is the process of associating or registering a name for a remote object, which can be used at a later time, in order to look up that remote object. A remote object can be associated with a name using the bind or rebind methods of the Naming class.

115. What is the difference between using bind() and rebind() methods of Naming Class?

The bind method bind is responsible for binding the specified name to a remote object, while the rebind method is responsible for rebinding the specified name to a new remote object. In case a binding exists for that name, the binding is replaced.

116. What are the steps involved to make work a RMI program?

The following steps must be involved in order for a RMI program to work properly:

  • Compilation of all source files.
  • Generation of the stubs using rmic.
  • Start the rmiregistry.
  • Start the RMIServer.
  • Run the client program.
150个Java面试问答-最终清单(PDF下载)_第8张图片 RMI Flow

117. What is the role of stub in RMI?

A stub for a remote object acts as a client's local representative or proxy for the remote object. The caller invokes a method on the local stub, which is responsible for executing the method on the remote object. When a stub's method is invoked, it undergoes the following steps:

  • It initiates a connection to the remote JVM containing the remote object.
  • It marshals the parameters to the remote JVM.
  • It waits for the result of the method invocation and execution.
  • It unmarshals the return value or an exception if the method has not been successfully executed.
  • It returns the value to the caller.

118. What is DGC and how does it work?

DGC stands for Distributed Garbage Collection. Remote Method Invocation (RMI) uses DGC for automatic garbage collection. Since RMI involves remote object references across JVMs, garbage collection can be quite difficult. DGC uses a reference counting algorithm to provide automatic memory management for remote objects.

119. What is the purpose of using RMISecurityManager in RMI?

RMISecurityManager provides a security manager that can be used by RMI applications, which use downloaded code. The class loader of RMI will not download any classes from remote locations, if the security manager has not been set.

120. Explain Marshalling and demarshalling.

When an application wants to pass its memory objects across a network to another host or persist it to storage, the in-memory representation must be converted to a suitable format. This process is called marshalling and the revert operation is called demarshalling.

121. Explain Serialization and Deserialization.

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes and includes the object's data, as well as information about the object's type, and the types of data stored in the object. Thus, serialization can be seen as a way of flattening objects, in order to be stored on disk, and later, read back and reconstituted. Deserialisation is the reverse process of converting an object from its flattened state to a live object.

K.Servlets

122. What is a Servlet?

The servlet is a Java programming language class used to process client requests and generate dynamic web content. Servlets are mostly used to process or store data submitted by an HTML form, provide dynamic content and manage state information that does not exist in the stateless HTTP protocol.

123. Explain the architecture of a Servlet.

The core abstraction that must be implemented by all servlets is the javax.servlet.Servlet interface. Each servlet must implement it either directly or indirectly, either by extending javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet. Finally, each servlet is able to serve multiple requests in parallel using multithreading.

150个Java面试问答-最终清单(PDF下载)_第9张图片 Servlet Architecture

124. What is the difference between an Applet and a Servlet?

An Applet is a client side java program that runs within a Web browser on the client machine. On the other hand, a servlet is a server side component that runs on the web server.An applet can use the user interface classes, while a servlet does not have a user interface. Instead, a servlet waits for client's HTTP requests and generates a response in every request.

125. What is the difference between GenericServlet and HttpServlet?

GenericServlet is a generalized and protocol-independent servlet that implements the Servlet and ServletConfig interfaces. Those servlets extending the GenericServlet class shall override the service method. Finally, in order to develop an HTTP servlet for use on the Web that serves requests using the HTTP protocol, your servlet must extend the HttpServlet instead. Check Servlet examples here .

126. Explain the life cycle of a Servlet.

On every client's request, the Servlet Engine loads the servlets and invokes its init methods, in order for the servlet to be initialized. Then, the Servlet object handles all subsequent requests coming from that client, by invoking the service method for each request separately. Finally, the servlet is removed by calling the server's destroy method.

150个Java面试问答-最终清单(PDF下载)_第10张图片 Servlet Lifecycle

127. What is the difference between doGet() and doPost()?

doGET: The GET method appends the name-value pairs on the request's URL. Thus, there is a limit on the number of characters and subsequently on the number of values that can be used in a client's request. Furthermore, the values of the request are made visible and thus, sensitive information must not be passed in that way. doPOST: The POST method overcomes the limit imposed by the GET request, by sending the values of the request inside its body. Also, there is no limitations on the number of values to be sent across. Finally, the sensitive information passed through a POST request is not visible to an external client.

The code below shows the BasicServlet class which has doGet and doPost methods to be implemented.

Get and Post methods

public class BasicServlet extends HttpServlet 
{
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
      {
      
      }
      
    public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
      {
      
      }      
      
}

128. What is meant by a Web Application?

A Web application is a dynamic extension of a Web or application server. There are two types of web applications: presentation-oriented and service-oriented. A presentation-oriented Web application generates interactive web pages, which contain various types of markup language and dynamic content in response to requests. On the other hand, a service-oriented web application implements the endpoint of a web service. In general, a Web application can be seen as a collection of servlets installed under a specific subset of the server's URL namespace.

129. What is a Server Side Include (SSI)?

Server Side Includes (SSI) is a simple interpreted server-side scripting language, used almost exclusively for the Web, and is embedded with a servlet tag. The most frequent use of SSI is to include the contents of one or more files into a Web page on a Web server. When a Web page is accessed by a browser, the Web server replaces the servlet tag in that Web page with the hyper text generated by the corresponding servlet.

130. What is Servlet Chaining?

Servlet Chaining is the method where the output of one servlet is sent to a second servlet. The output of the second servlet can be sent to a third servlet, and so on. The last servlet in the chain is responsible for sending the response to the client.

131. How do you find out what client machine is making a request to your servlet?

The ServletRequest class has functions for finding out the IP address or host name of the client machine. getRemoteAddr() gets the IP address of the client machine and getRemoteHost() gets the host name of the client machine. See example here .

132. What is the structure of the HTTP response?

The HTTP response consists of three parts:

  • Status Code: describes the status of the response. It can be used to check if the request has been successfully completed. In case the request failed, the status code can be used to find out the reason behind the failure. If your servlet does not return a status code, the success status code, HttpServletResponse.SC_OK, is returned by default.
  • HTTP Headers: they contain more information about the response. For example, the headers may specify the date/time after which the response is considered stale, or the form of encoding used to safely transfer the entity to the user. See how to retrieve headers in Servlet here .
  • Body: it contains the content of the response. The body may contain HTML code, an image, etc. The body consists of the data bytes transmitted in an HTTP transaction message immediately following the headers.

133. What is a cookie?

A cookie is a bit of information that the Web server sends to the browser. The browser stores the cookies for each Web server in a local file. In a future request, the browser, along with the request, sends all stored cookies for that specific Web server.

134. What is the difference between session and cookie?

The differences between session and a cookie are the following:

  • The session should work, regardless of the settings on the client browser. The client may have chosen to disable cookies. However, the sessions still work, as the client has no ability to disable them in the server side.
  • The session and cookies also differ in the amount of information the can store. The HTTP session is capable of storing any Java object, while a cookie can only store String objects.

135. Which protocol will be used by browser and servlet to communicate?

The browser communicates with a servlet by using the HTTP protocol.

136. What is HTTP Tunneling?

HTTP Tunneling is a technique by which, communications performed using various network protocols are encapsulated using the HTTP or HTTPS protocols. The HTTP protocol therefore acts as a wrapper for a channel that the network protocol being tunneled uses to communicate. The masking of other protocol requests as HTTP requests is HTTP Tunneling.

137. What's the difference between sendRedirect and forward methods?

The sendRedirect method creates a new request, while the forward method just forwards a request to a new target. The previous request scope objects are not available after a redirect, because it results in a new request. On the other hand, the previous request scope objects are available after forwarding. FInally, in general, the sendRedirect method is considered to be slower compare to the forward method.

SendRedirect Forward
This method sends a new request always. Th is because it uses the URL bar of the browser for redirecting. This method sends the request to another resource by forwarding it.
This method is used at client side. This method is usead at server side.
This method is used inside and outside the web server. This method is used inside the web server only.

138. What is URL Encoding and URL Decoding?

The URL encoding procedure is responsible for replacing all the spaces and every other extra special character of a URL, into their corresponding Hex representation. In correspondence, URL decoding is the exact opposite procedure.

139. What is Request Dispatcher?

Servlet Request Dispatcher is an interface whose implementation defines that an object can dispatch requests to any resource (such as HTML, Image, JSP, Servlet etc.) on the server. Another advantage of this interface is that it is used in two cases:

  • To include the response of one Servlet into another (ie the client gets the response of both Servlets)
  • To forward the client request to another Servlet to honor the request (ie the client calls a Servlet but the response to client is given by another Servlet)

L.JSP

140. What is a JSP Page?

A Java Server Page ( JSP ) is a text document that contains two types of text: static data and JSP elements. Static data can be expressed in any text-based format, such as HTML or XML. JSP is a technology that mixes static content with dynamically-generated content. See JSP example here .

141. How are the JSP requests handled?

On the arrival of a JSP request, the browser first requests a page with a .jsp extension. Then, the Web server reads the request and using the JSP compiler, the Web server converts the JSP page into a servlet class. Notice that the JSP file is compiled only on the first request of the page, or if the JSP file has changed.The generated servlet class is invoked, in order to handle the browser's request. Once the execution of the request is over, the servlet sends a response back to the client. See how to get Request parameters in a JSP .

142. What are the advantages of JSP?

The advantages of using the JSP technology are shown below:

  • JSP pages are dynamically compiled into servlets and thus, the developers can easily make updates to presentation code.
  • JSP pages can be pre-compiled.
  • JSP pages can be easily combined to static templates, including HTML or XML fragments, with code that generates dynamic content.
  • Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.
  • Developers can make logic changes at the component level, without editing the individual pages that use the application's logic.

143. What are Directives?

Directives are instructions that are processed by the JSP engine, when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries.

144. What are the different types of Directives available in JSP?

Directives are defined between < %@ and % >.The different types of directives are shown below:

  • Include directive: it is used to include a file and merges the content of the file with the current page.
  • Page directive: it is used to define specific attributes in the JSP page, like error page and buffer.
  • Taglib: it is used to declare a custom tag library which is used in the page.

145. What are JSP actions?

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. They are executed when a JSP page is requested. They can be dynamically inserted into a file, re-use JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.Some of the available actions are listed below:

  • jsp:include includes a file, when the JSP page is requested.
  • jsp:useBean finds or instantiates a JavaBean.
  • jsp:setProperty sets the property of a JavaBean.
  • jsp:getProperty gets the property of a JavaBean.
  • jsp:forward forwards the requester to a new page.
  • jsp:plugin generates browser-specific code.

146. What are Scriptlets?

In Java Server Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in a JSP page. The scriptlet is everything inside the tags. Between these tags, a user can add any valid scriptlet.

147. What are Declarations?

Declarations are similar to variable declarations in Java. Declarations are used to declare variables for subsequent use in expressions or scriptlets. To add a declaration, you must use the sequences to enclose your declarations.

Sample code is added below to show the JSP declarations.

Declarations

<%! int j = 0; %> 
<%! int d, e, f; %> 
<%! Shape a = new Shape(); %>

148. What are Expressions?

A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client, by the web server. Expressions are defined between <% = and %> tags.

JSP Expresssion

 
   My Blog 
   
   
      

Today's Date is: <%= (new java.util.Date()).toLocaleString()%>

149. What is meant by implicit objects and what are they?

JSP implicit objects are those Java objects that the JSP Container makes available to developers in each page. A developer can call them directly, without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.The following objects are considered implicit in a JSP page:

  • 应用
  • request
  • 响应
  • session
  • 例外
  • 配置
  • pageContext

JSP sample tags for disabling session is shown below:

Disabling Session

<%@ page session=“false” %>

150. What are the different tags provided in JSTL?

There are 5 type of JSTL tags:

Core:

  • Variable support
  • 流量控制
  • URL management

XML:

  • 核心
  • 流量控制
  • 转型

Internationalization:

  • 语言环境
  • Message formatting
  • Number and date formatting

Database:

  • 的SQL

功能:

  • Collection length
  • String manipulation

Want more Java interview questions?

你还在和我们在一起吗? Wow, that was a huge article about different types Java Interview Questions. 如果您喜欢此功能,请订阅我们的时事通讯,以享受每周更新和免费白皮书! 另外,请查看我们的课程以获得更高级的培训!

So, what other Java Interview Questions are there? 在评论中让我们知道,我们将在文章中添加它们! 编码愉快!

Java Interview Questions was last updated on Aug. 07th, 2019

翻译自: https://www.javacodegeeks.com/java-interview-questions.html

你可能感兴趣的:(编程语言,java,jvm,面试,多线程)