Java 简明教程
Java Interview Questions and Answers
如果您正在寻找 Java 面试问题?我们在这里为您提供帮助,利用 200 多个面试问答来增强您对 Java 编程语言的了解。我们首先了解一下 Java。
If you are looking for Java Interview Questions? We are here to help you, to enhance your knowledge of Java programming language with the help of 200+ interview questions and answers. Let’s learn what is Java, first.
What is Java?
Java programming language 最初由 Sun Microsystem 开发,由 James Gosling 发起,并于 1995 年作为 Sun Microsystems Java 平台(Java 1.0 [J2SE])的核心组件发布。Java Standard Edition 的最新版本是 Java SE 8。随着 Java 的进步及其广泛普及,已构建多种配置以适应各种类型的平台。例如,针对企业应用程序的 J2EE,针对移动应用程序的 J2ME。
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as the core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]). The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example, J2EE for Enterprise Applications, and J2ME for Mobile Applications.
Interview Questions and Answers on Core and Advanced Java
查找 200 多个重要的 Java 面试问题以及答案。这些 Java interview questions are based-on Core and advanced Java programming 等主题,如核心 Java 概念、 Object-Oriented Programming (OOP) 、 Java Collections Framework 、 Multithreading 、Java I/O、 Exception Handling 、Java 内存管理、Java 注解、Java 设计模式、 Java Streams API JDBC 等等。这些用于 Java 面试的问题由主题专家准备,学生和开发者可以学习并练习这些问题,从而获得顶级 IT 公司的选拔。
Find the list of 200+ important Java interview questions along with the answers. These Java interview questions are based-on Core and advanced Java programming topics such as Core Java Concepts, Object-Oriented Programming (OOP), Java Collections Framework, Multithreading, Java I/O, Exception Handling, Java Memory Management, Java Annotations, Java Design Patterns, Java Streams API, JDBC, and many more. These questions for Java interviews are prepared by the subject experts and can be practiced by the students and developers to practice, learn, and get selected by the top IT companies.
我们将这些问题分为 3 部分。让我们练习 interview questions and answers on Java programming language:
We have categorized these questions into 3 sections. Let’s practice the interview questions and answers on Java programming language:
Java Interview Questions and Answers for Freshers
Java 是一种高级编程语言,最初由 Sun Microsystems 开发并于 1995 年发布。Java 可以在各种平台上运行,例如 Windows、Mac OS 和各种版本的 UNIX。
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
Java 可以在各种平台上运行,例如 Windows、Mac OS 和各种版本的 UNIX/Linux,如 HP-Unix、Sun Solaris、Redhat Linux、Ubuntu、CentOS 等。
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.
某些功能包括面向对象、平台独立、健壮、解释、多线程
Some features include Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded
另请阅读: Java features
Read also: Java features
它的编译器生成架构中立的对象文件格式,这使得编译后的代码可以在许多处理器上执行,并存在 Java 运行时系统。
It’s compiler generates an architecture-neutral object file format, which makes the compiled code to be executable on many processors, with the presence of Java runtime system.
Java 使用即时编译器实现高性能。即时编译器是一个程序,它将 Java 字节码(一个包含必须解释为可直接发送到处理器的指令的程序)转换为指令。
Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode, which is a program that contains instructions that must be interpreted into instructions that can be sent directly to the processor.
它旨在适应不断变化的环境。Java 程序可以携带大量运行时信息,这些信息可用于验证和解析在运行时对对象的访问。
It is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
当编译 Java 时,它不是将其编译为特定的机器平台,而是编译为与平台无关的字节码。这个字节码被分布到网络上,并且由 Java virtual Machine (JVM) 在任何运行它的平台上进行解释。
When Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by Java virtual Machine (JVM) on whichever platform it is being run.
两个重要且常用的 Java IDE 是 Netbeans 和 Eclipse。
The two important and commonly used Java IDE’s are Netbeans and Eclipse.
一些 Java 关键字是 import、super、finally 等。
Some Java keywords are import, super, finally, etc.
Object is a runtime entity and it’s state is stored in fields and behavior is shown via methods. Methods operate on an object’s internal state and serve as the primary mechanism for object-to-object communication.
类是一个蓝图,从中创建各个对象。类可以包含字段和方法来描述对象的的行为。
A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.
Read also: Java - Classes and Objects
一个类包含局部变量,实例变量和类变量。
A class consist of Local variable, instance variables and class variables.
另请阅读: Java Variable Types
Read also: Java Variable Types
在 methods 、 constructors 或块中定义的变量称为局部变量。变量将在方法中声明并初始化,并且当方法完成时将被销毁。
Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.
实例变量是类中的变量,但位于任何方法之外。这些变量在加载类时被实例化。
Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.
这些是在类中声明的变量,位于任何方法之外,并带有 static 关键字。
These are variables declared with in a class, outside any method, with the static keyword.
Singleton class 控制对象创建,将数量限制为一个,但允许在情况变化时创建更多对象。
Singleton class control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.
Java constructor 在新建对象时调用。每个类都有一个构造函数。如果我们没有为一个类明确编写构造函数,java 编译器会为该类构建一个默认构造函数。
Java constructor gets invoked when a new object is created. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.
首先声明一个对象,然后实例化它,之后初始化它。
An Object is first declared, then instantiated and then it is initialized.
字节数据类型的默认值为 0。另请阅读: Java Data Types
Default value of byte datatype is 0. Read also: Java Data Types
在 Java 中,float 的默认值为 0.0f,double 的默认值为 0.0d。
In Java, the default value of float is 0.0f and the default value of double is 0.0d.
*byte*数据类型用于在大型数组中节省空间,主要用在整数的位置上,因为一个字节比一个 int 小四倍。
The byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.
类变量也称为静态变量,在类中使用 static keyword 声明,但位于方法、构造函数或代码块之外。
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
Java 提供 access modifiers 来为类、变量、 methods 和 constructors 设置访问级别。当未指定访问修饰符时,成员具有包或默认可访问性。
Java provides access modifiers to set access levels for classes, variables, methods and constructors. A member has package or default accessibility when no accessibility modifier is specified.
在超类中声明为受保护的变量、方法和构造函数只能由其他包中的子类或受保护成员类包中的任何类访问。
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
Java 提供了这些修饰符,用于提供除访问修饰符之外的功能,synchronized 用于指示可以一次仅被一个线程访问的方法。
Java provides these modifiers for providing functionalities other than Access Modifiers, synchronized used to indicate that a method can be accessed by only one thread at a time.
后缀运算符,即 () [] . 优先级最高。
Postfix operators i.e () [] . is at the highest precedence.
在 switch 语句中使用的变量只能是字符串、枚举、字节、短整型、整型或字符。
Variables used in a switch statement can only be a string, enum, byte, short, int, or char.
Java parseInt() method 用于获取特定字符串的基本数据类型。
Java parseInt() method is used to get the primitive data type of a certain String.
Java String class 是不可变的,因此一旦创建后字符串对象就无法更改。由于字符串是不可变的,因此可以在许多线程之间安全地共享它,这对于多线程编程非常重要。
Java String class is immutable, so that once it is created a String object cannot be changed. Since String is immutable it can safely be shared between many threads ,which is considered very important for multithreaded programming.
Java String class 被认为是不可变的,因此一旦创建后字符串对象就无法更改。如果需要对字符串字符进行大量修改,则应使用 StringBuffer。
Java String class is considered as immutable, so that once it is created a String object cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be used.
尽可能使用 StringBuilder ,因为它比 StringBuffer 更快。但如果需要线程安全,则应使用 StringBuffer 对象。
Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary then use StringBuffer objects.
java.util.regex 包用于通过 regular expressions 进行模式匹配。
java.util.regex package is used for pattern matching with regular expressions.
java.util.regex 包含三个类:Pattern 类、Matcher 类和 PatternSyntaxException 类。
java.util.regex consists of three classes − Pattern class, Matcher class and PatternSyntaxException class.
可以通过方法来定义对象在垃圾回收器执行最终销毁之前要调用的方法。该方法称为 finalize(),可用于确保对象正确终止。
It is possible to define a method that will be called just before an object’s final destruction by the garbage collector. This method is called finalize(), and it can be used to ensure that an object terminates cleanly.
exception 是在程序执行期间出现的某个问题。可以通过沿线程方法调用堆栈放置的处理程序捕获异常。
An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread’s method invocation stack.
它是一种异常,通常是用户错误或程序员无法预见的问题。例如,如果要打开一个文件,但是该文件找不到,将发生一个异常。在编译时不能简单地忽略这些异常。
It is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
它是一种异常,可能可以通过编程人员来避免。与检查异常相反,运行时异常在编译时被忽略。
It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Exception 类有两个主要的子类:IOException 类和 RuntimeException 类。
The Exception class has two main subclasses : IOException class and RuntimeException Class.
如果没有方法处理已检查的异常,则必须使用 throws keyword 声明该方法。throws 关键字显示在方法签名的末尾。
If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.
可以使用 throw keyword 抛出异常,无论是新实例化的异常还是刚才捕获的异常。
An exception can be thrown, either a newly instantiated one or an exception that you just caught, by using throw keyword.
finally keyword 用于创建紧接在 try 块后面的代码块。无论是否发生异常,finally 代码块始终执行。
The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
在创建你自己的异常时:
While creating your own exception −
-
All exceptions must be a child of Throwable.
-
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
-
You want to write a runtime exception, you need to extend the RuntimeException class.
Inheritance 是一个对象获取另一个对象属性的过程。通过使用继承,信息将按照层次顺序进行管理。
Inheritance is the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
如果方法覆盖其超类的某个方法,则可以通过使用 keyword super 来调用覆盖的方法。也可以使用它来引用隐藏的字段。
If the method overrides one of its superclass’s methods, overridden method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field.
Polymorphism 是对象采用多种形式的能力。OOP 中最常见的多态性用法是当父类引用用于引用子类对象时。
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Abstraction 指 OOP 中生成抽象类的能力。有助于降低复杂性,并提高系统的可维护性。
Abstraction refers to the ability to make a class abstract in OOP. It helps to reduce the complexity and also improves the maintainability of the system.
这些类不能实例化,并且完全没有实现或部分实现。该类包含一个或多个抽象方法,这些方法只是不包含主体的方法声明。
These classes cannot be instantiated and are either partially implemented or not at all implemented. This class contains one or more abstract methods which are simply method declarations without a body.
如果你想让一个类包含某一个特定方法,但希望该方法的实际实现由子类来确定,那么你可以在父类中声明该方法是抽象方法。
If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.
Encapsulation 是使类中的字段私有化,并通过公共方法提供对这些字段的访问的技术。如果字段声明为私有,则类外部的任何人均无法访问该字段,从而将该字段隐藏在类中。因此,封装也被称为数据隐藏。
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. Therefore encapsulation is also referred to as data hiding.
封装的主要好处是能够修改我们的已实现代码,而不会破坏其他使用我们代码的代码。这样,封装就将可维护性、灵活性及可扩展性赋予我们的代码。
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our code.
Java Interview Questions and Answers for Experienced
Java interface 是抽象方法的集合。类实现某个接口,从而继承该接口的抽象方法。
Java interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
Java 接口的一些特性:
Some of the features of Java interface are:
-
Interface cannot be instantiated
-
An interface does not contain any constructors.
-
All of the methods in an interface are abstract.
Java Package 可以定义为提供访问保护和名称空间管理的相关类型(类、接口、枚举和注释)的分组。
Java Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.
Java 中使用包是为了防止命名冲突、控制访问、简化对类、接口、枚举和注解等的搜索/定位和使用。
Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations, etc., easier.
多线程程序包含可并发运行的两个或多个部分。该程序的每个部分称为一个线程,每个线程定义一条独立的执行路径。
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
可以创建线程,方法如下:实现 Runnable 接口、扩展 Thread class。
Thread can be created by: implementing Runnable interface, extending the Thread class.
applet 是在 Web 浏览器中运行的 Java 程序。Applet 可以是全功能 Java 应用程序,因为它可以自由使用整个 Java API。
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal.
Applet 扩展 java.applet.Applet 类。
An applet extends java.applet.Applet class.
它使用垃圾回收功能来释放内存。通过清理所有不再被任何程序引用的对象。
It uses garbage collection to free the memory. By cleaning those objects that is no longer reference by any of the program.
不可变对象一旦创建就不能更改。
An immutable object can’t be changed once it is created.
与变量或方法一起使用,用于调用同类构造函数。
It is used with variables or methods and used to call constructer of same class.
Java Set interface 是元素的集合,不包含重复元素。Set 接口仅包含从 Collection 继承的方法,并添加了禁止重复元素的限制。
Java Set interface is a collection of element which cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
当我们希望元素按排序顺序排列时,会实现 Set。
It is a Set implemented when we want elements in a sorted order.
Java Comparable Interface 用于使用 collections.sort() 和 java.utils 对对象集合和数组进行排序。可以通过实现 Comparable 接口的类的对象进行排序。
Java Comparable Interface is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered.
它包括:
It includes:
-
Throw is used to trigger an exception where as throws is used in declaration of exception.
-
Without throws, Checked exception cannot be handled where as checked exception can be propagated with throws.
以下分别显示了解释 −
The following shows the explanation individually −
-
public − it is the access specifier.
-
static − it allows main() to be called without instantiating a particular instance of a class.
-
void − it affirns the compiler that no value is returned by main().
-
main() − this method is called at the beginning of a Java program.
-
String args[ ] − args parameter is an instance array of class String
Java 运行时环境是 Java Virtual Machine 的实现,执行 Java 程序。它提供了执行 Java 应用程序的最低要求;
Java Runtime Environment is an implementation of the Java Virtual Machine which executes Java programs. It provides the minimum requirements for executing a Java application;
JAR 文件是 Java 归档文件,它将许多文件聚合为一个文件。它在库中保存 Java 类。JAR 文件基于 ZIP 文件格式,并且具有 .jar 文件扩展名。
JAR files is Java Archive fles and it aggregates many files into one. It holds Java classes in a library. JAR files are built on ZIP file format and have .jar file extension.
这是 Web 归档文件,用于存储 XML、Java 类和 JavaServer 页面。用于分发 JavaServer 页面、Java Servlet、Java 类、XML 文件、静态 Web 页面等的集合。
This is Web Archive File and used to store XML, java classes, and JavaServer pages. which is used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages etc.
它可以根据字节码改善计算机程序的运行时性能。
It improves the runtime performance of computer programs based on bytecode.
基于对象的编程语言遵循面向对象编程语言 (OOPs) 除继承之外的所有功能。JavaScript 是基于对象的编程语言的一个示例。
Object based programming languages follow all the features of OOPs except Inheritance. JavaScript is an example of object based programming languages.
只有当类中没有构造器时,Java 编译器才会创建一个默认构造器。
The java compiler creates a default constructor only if there is no constructor in the class.
不行,不可能。
No, this is not possible.
它用于初始化静态数据成员,它在类加载时在 main 方法之前执行。
It is used to initialize the static data member, It is excuted before main method at the time of classloading.
在某个类中持有其他类的引用称为合成。
Holding the reference of the other class within some other class is known as composition.
如果某个类具有多个同名函数,但参数不同,则称为 Method Overloading。
If a class has multiple functions by same name but different parameters, it is known as Method Overloading.
如果一个子类为其父类已经提供的某个方法提供具体的实现,则将之称为 Method Overriding。
If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding.
方法重载提高了程序的可读性。方法重写提供了由其超类已经提供的方法的特定实现,在重载的情况下参数必须不同,在重写的情况下参数必须相同。
Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class parameter must be different in case of overloading, parameter must be same in case of overriding.
创建 final 类,这样该类实现的方法就不能被重写。它不能被继承。
Final classes are created so the methods implemented by that class cannot be overridden. It can’t be inherited.
当调用空对象的实例方法、访问或修改空对象的字段等时,将抛出 NullPointerException。
A NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object etc.
线程可以通过调用其 sleep() 方法、阻止 IO、尝试获取对象锁失败或调用 object’s wait() method 来进入等待状态。它还可以通过调用其(已弃用的)suspend() 方法来进入等待状态。
A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
操作系统的任务调度器将执行时间分配给多个任务。通过在执行任务之间快速切换,它会造成任务顺序执行的印象。
The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
通过 Thread 类的 start() 方法启动线程后,在最初执行线程时,JVM 会调用线程的 run() 方法。
After a thread is started, via its start() method of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.
是的,确实是这样。FileNoFoundException 继承自 IOException。必须先捕获异常的子类。
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception’s subclasses have to be caught first.
当任务调用其 yield() 方法时,它会返回就绪状态。当任务调用其 sleep() 方法时,它会返回等待状态。
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
Vector class 提供实现可增长对象的数组的功能。如果您事先不知道数组的大小,或者只需要一个可以在程序的生命周期中更改大小的数组,则 Vector 被证明非常有用。
The Vector class provides the capability to implement a growable array of objects. Vector proves to be very useful if you don’t know the size of the array in advance, or you just need one that can change sizes over the lifetime of a program.
Unicode 需要 16 位,ASCII 需要 7 位。虽然 ASCII 字符集仅使用 7 位,但它通常表示为 8 位。UTF-8 使用 8 位、16 位和 18 位模式表示字符。UTF-16 使用 16 位和更大的位模式。
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
这些类允许基本类型以对象的形式访问。示例:Integer、Character、Double、Boolean 等。
These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double, Boolean etc.
Frame 类扩展 Window,以定义一个可以有菜单栏的主应用程序窗口。
The Frame class extends Window to define a main application window that can have a menu bar.
javax.Swing 包。Swing 中的所有组件(JApplet、JDialog、JFrame 和 JWindow 除外)都是轻量级组件。
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
paint() 方法通过 Graphics 对象支持绘制。repaint() 方法用于导致 paint() 由 AWT 绘图线程调用。
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
它用于创建提供对本地文件系统中的文件和目录的访问权限的对象。
It is used to create objects that provide access to the files and directories of a local file system.
Reader/Writer 类层次结构以字符为导向,InputStream/OutputStream 类层次结构以字节为导向。
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
Class 类用于获取有关对象的设计的的信息,并且 java.lang.Class 类实例表示正在运行的 Java 应用程序中的类和接口。
The Class class is used to obtain information about an object’s design and java.lang.Class class instance represent classes, interfaces in a running Java application.
静态变量与整个类相关联,而不是与类的特定实例相关联。非静态变量对每个对象实例采用唯一值。
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
序列化是将对象状态写入字节流的过程。反序列化是恢复这些对象的过程。
Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
它是程序分析的一部分,描述了程序可能遇到的情况以及程序在该情况下应表现出的行为。
It is part of the analysis of a program and describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance.
子类继承所有公共和受保护的方法以及实现。它还继承所有默认修饰符方法及其实现。
Sub class inherits all the public and protected methods and the implementation. It also inherits all the default modifier methods and their implementation.
如果有称为 b1 的按钮实例,则可以通过调用 b1.setMnemonic('F') 添加菜单快捷方式,以便用户可以使用 Alt+F 单击此按钮。
If there is a button instance called b1, you may add menu short cut by calling b1.setMnemonic('F'), so the user may be able to use Alt+F to click the button.
是的,只需为小程序添加 main() 方法即可。
Yes, just add a main() method to the applet.
Advanced Java Interview Questions and Answers
AWT 组件是重量级的,而 Swing 组件是轻量级的。重量级组件依赖于本地窗口工具包。例如,java.awt.Button 是一个重量级组件,当它在适用于 Unix 平台的 Java 平台上运行时,它会映射到一个真实的 Motif 按钮。
AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.
构造函数必须与类同名,且不能返回值。它们仅调用一次,而常规方法可以调用多次。
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.
是的,由于继承继承了超类和接口的所有内容,因此在某些情况下进行动态覆盖或动态重载时,它可能使子类过于聚合且有时容易出错。
Yes, since inheritance inherits everything from the super class and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation.
在不同数组之间复制元素时,如果源或目标参数不是数组或其类型不兼容,则将抛出 ArrayStoreException。
When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.
是的,使用 this() 语法。
Yes, use this() syntax.
sleep(2000) 代码将线程搁置两秒钟。wait(2000) 代码导致最多两秒钟的等待。如果线程收到 notify() 或 notifyAll() 调用,则线程可能会提前停止等待。wait() 方法在类 Object 中定义,sleep() 方法在类 Thread 中定义。
The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
当整数除以零或取余数为零时,引发 ArithmeticException。它不会在浮点运算中引发。
The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.
短暂变量是一个变量,它可能不会在序列化期间序列化,并且在反序列化期间由其默认值初始化。
A transient variable is a variable that may not be serialized during Serialization and which is initialized by its default value during de-serialization,
同步是控制多线程访问共享资源的能力。java 中的 synchronized 关键字提供锁定,它确保了共享资源的互斥访问并防止数据竞争。
Synchronization is the capability to control the access of multiple threads to shared resources. synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race.
Collections API 是一组类和接口,它们支持对对象集合上的操作。
The Collections API is a set of classes and interfaces that support operations on collections of objects.
垃圾回收并不能保证程序不会耗尽内存。程序可能消耗内存资源的速度快于它们被垃圾回收的速度。程序也可能创建不受垃圾回收影响的对象。
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.
面板是直接的超类。面板提供一个空间,应用程序可以在其中附加任何其他组件,包括其他面板。
Panel is the immediate superclass. A panel provides space in which an application can attach any other component, including other panels.
运算符是右结合。
The = operator is right associative.
break 语句会导致应用该语句的语句终止(switch、for、do 或 while)。continue 语句用于结束当前循环迭代并返回对循环语句的控制。
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
私有变量只能在声明它的类中访问。
A private variable may only be accessed within the class in which it is declared.
System 类的目的是提供对系统资源的访问。
The purpose of the System class is to provide access to system resources.
八种原始类型是 byte、char、short、int、long、float、double 和 boolean。
The eight primitive types are byte, char, short, int, long, float, double, and boolean.
当窗口被 AWT 绘制线程重新绘制时,它将剪辑区域设置成需要重新绘制的窗口区域。
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.
Component 类是直接的超类。
Component class is the immediate super class.
Java 运行时系统生成 RuntimeException 和 Error 异常。
The Java runtime system generates RuntimeException and Error exceptions.
垃圾收集器在检测到对象变得不可达时调用对象的 finalize() 方法。
The garbage collector invokes an object’s finalize() method when it detects that the object has become unreachable.
不可重新启动死线程。
A dead thread cannot be restarted.
Integer / 和 % 可能导致抛出 ArithmeticException。
Integer / and % can result in the throwing of an ArithmeticException.
boolean 类型的默认值是 false。
The default value of the boolean type is false.
是
Yes
类加载器是一个负责加载类的对象。ClassLoader 类是一个抽象类。
A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class.
抽象类可以有实例方法来实现默认行为。接口只能声明常量和实例方法,但不能实现默认行为,并且所有方法都是隐式抽象的。接口具有所有公共成员且没有实现。
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation.
程序在运行时抛出“NoSuchMethodError”错误。
Program throws "NoSuchMethodError" error at runtime.
null,除非显式定义。
Null, unless it is defined explicitly.
否,顶级类不能是私有或受保护的。它可以具有“public”或没有修饰符。
No, a top level class can not be private or protected. It can have either "public" or no modifier.
当某个方法期望一个对象时,我们可以将它们传递为方法参数。 wrapper class 还提供了实用程序方法。
We can pass them around as method parameters where a method expects an object. The wrapper class also provides utility methods.
错误是在运行时发生的不可恢复状态。例如 OutOfMemory 错误。异常是因错误输入等原因出现的条件。例如,如果指定的 file 不存在,那么将抛出 FileNotFoundException。
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.
并非每个 try 块都需要后跟一个 catch 块。它应该后跟 catch 块或 finally 块。
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block or a finally block.
线程在其创建和启动后的初始状态为 ready 状态。
A thread is in the ready state as initial state after it has been created and started.
Locale 类用于根据特定地理、政治或文化区域的惯例定制程序输出。
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
同步方法是用于控制对对象访问的方法。只有在某个线程获取了 synchronized 语句中引用的对象或类的锁时,才能执行 synchronized 语句。
Synchronized methods are methods that are used to control access to an object. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
运行时多态性或动态方法分派是将对重写方法的调用在运行时而不是编译时求解的过程。在此过程中,重写方法是通过超类引用变量调用的。
Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass.
绑定是指将过程调用链接到对该调用进行响应的要执行的代码。动态绑定意味着与给定过程调用关联的代码直到运行时,在调用时才知道。
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time.
不,构造函数不能被继承。
No, constructor cannot be inherited.
与数组相比,ArrayList 可以动态增长并且提供更强大的插入和搜索机制。
ArrayList can grow dynamically and provides more powerful insertion and search mechanisms than arrays.
在链表中进行删除速度很快,因为它只涉及更新被删除节点前节点的 next 指针,以及更新被删除节点后节点的 previous 指针。
Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
如果你需要经常在列表中间添加和删除元素,并且只会按顺序访问列表元素,那么则应该使用 LinkedList。如果你需要支持随机访问,而无需在除末尾之外的任何位置插入或删除元素,那么则应该使用 ArrayList。
If you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList should be used. If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList should be used.
它是由 Map 接口的 values() 方法返回的集合,它包含所有在 map 中作为值的 object。
It is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map.
点运算符 (.) 用于访问类对象的实例变量和方法。它还用于从包中访问类和子包。
The dot operator(.) is used to access the instance variables and methods of class objects.It is also used to access classes and sub-packages from a package.
如果不想让其他类实例化 object 并且要防止子类化,那么可以使用 private 构造函数。
Private constructor is used if you do not want other classes to instantiate the object and to prevent subclassing.T
类型转换是指将一种类型的变量当作另一种类型对待。
Type casting means treating a variable of one type as though it is another type.
线程是程序中的一个执行单元。线程的生命周期包括:
A thread is a execution in a program. The life cycle of a thread include −
-
Newborn state
-
Runnable state
-
Running state
-
Blocked state
-
Dead state
>> 运算符在右移时携带符号位。>>> 则以零填充已移出的位。
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
setBounds() 方法用于此目的。
setBounds() method is used for this purpose.
short 类型的范围为 -(2^15)至 2^15 - 1。
The range of the short type is -(2^15) to 2^15 - 1.
MenuItem 类
MenuItem class
不,Java 不允许使用默认参数。
No, Java does not allow Default Arguments.
八进制数在 Java 中以前导零表示,例如:06
Octal Numbers are denoted by leading zero in java, example: 06
十六进制数在 Java 中以前导 0x 或 0X 表示,例如 - 0XF
Hexadecimal Numbers are denoted by leading 0x or 0X in java, example − 0XF
是的,一个例子如下:break one;
Yes, an example can be break one;
import 语句允许在 package 语句后出现在程序文件的开头。
Import statement is allowed at the beginning of the program file after package statement.
它用于暂停或暂时停止线程执行。
It is used to pause or temporarily stop the execution of the thread.
它用于找出线程是否仍在运行。
It is used to find out whether a thread is still running or not.
这是一个用于获取对当前线程引用的公共静态方法。
It is a public static method used to obtain a reference to the current thread.
main 线程会自动创建,并且在程序开始时立即开始执行。它是所有其他子线程的源线程。
The main thread is created automatically and it begins to execute immediately when a program starts. It ia thread from which all other child threads originate.
生命周期涉及以下步骤 -
Life cycle involves the following steps −
-
Initialization
-
Starting
-
Stopping
-
Destroying
-
Painting
它初始化微程序,并且是第一个被调用的方法。
It initializes the applet and is the first method to be called.
getImage(URL 对象,文件名) 用于此目的。
getImage(URL object, filename) is used for this purpose.
它用于指定微程序类名。
It is used to specify the name of the applet class.
这是一个简单的绘图区域,用于绘图或执行其他图形操作。
It is a simple drawing surface which are used for painting images or to perform other graphical operations.
它指在多设备(计算机)上执行程序,这些设备都通过网络相互连接。
It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.
套接字使用 TCP 在两台计算机之间提供通信机制。客户端程序在其通信端创建套接字,并尝试将该套接字连接到服务器。
Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
套接字灵活且足够。基于套接字的高效编程可以轻松实现,用于通用通信。它会造成较低的网络流量。
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. It cause low network traffic.
基于套接字的通信仅允许在应用程序之间发送数据包的原始数据。客户端和服务端都必须提供机制,以使数据在任何情况下都有用。
Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
java.net.ServerSocket 类被服务器应用程序用于获取端口并侦听客户机请求
java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests
java.net.Socket 类表示用于客户端和服务器相互通信的套接字。
java.net.Socket class represents the socket that both the client and server use to communicate with each other.
泛型提供了编译时类型安全性,允许程序员在编译时捕获无效类型。Java 泛型方法和泛型类允许程序员通过单一方法声明指定一组相关方法,或通过单一类声明指定一组相关类型。
Generics provide compile-time type safety that allows programmers to catch invalid types at compile time. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types.
CLASSPATH 和 PATH 是两个变量。
CLASSPATH and PATH are the two variables.
不,无需导入此包。它默认情况下由 JVM 内部加载。
No, there is no need to import this package. It is by default loaded internally by the JVM.
如果一个类在另一个类中声明并指定 static 修饰符,编译器会将该类像其他顶级类一样对待。嵌套的顶级类是内部类。
If a class is declared within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Nested top-level class is an Inner class.
Externalizable 是一个包含 readExternal 和 writeExternal 两个方法的接口。这些方法使您可以控制序列化机制。
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism.
不,在这种情况下,finally 块不会执行,因为当您说 System.exit (0);时,控件会立即退出程序,因此 finally 永远不会执行。
No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.
守护线程是一个低优先级的线程,它间歇性地在后台运行,为 Java 运行时系统执行垃圾收集操作。
Daemon thread is a low priority thread, which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.
setDaemon 方法用于创建守护线程。
setDaemon method is used to create a daemon thread.
所有任务都必须实现 run() 方法
All tasks must implement the run() method
GregorianCalendar 为传统的西方日历提供支持
The GregorianCalendar provides support for traditional Western calendars
SimpleTimeZone 类为 Gregorian 日历提供支持。
The SimpleTimeZone class provides support for a Gregorian calendar .
size 是实际存储在向量中的元素数,而容量是在给定时间实例可以存储的最大元素数。
The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.
是的,向量可以包含异构对象。因为向量以对象的形式存储所有内容。
Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
枚举是一个包含用于从获得枚举的底层数据结构访问的方法的接口。它允许顺序访问存储在 collection 中的所有元素。
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection.
Path 和 Classpath 是操作系统级别的环境变量。Path 定义了系统可以在哪里找到可执行文件(.exe),而 classpath 用于指定 .class 文件的位置。
Path and Classpath are operating system level environment variales. Path is defines where the system can find the executables(.exe) files and classpath is used to specify the location of .class files.
不,无法访问包外。
No, it’s not possible to accessed outside it’s package.
静态方法不应引用实例变量,而无需创建实例,并且不能使用“this”运算符引用该实例。
A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.
是的 一个接口可以继承另一个接口,就那而言一个接口可以扩展多个接口。
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.
多态
Polymorphism
一个对象的锁是一个机制,由多个线程用来获取对该对象的同步访问。在获得这个对象的锁之后,一个线程才能执行该对象的一个同步方法。
An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock.
它是从一个通用的到一个更具体的类型,也就是说,沿层次结构向下转型。
It is the casting from a general to a more specific type, i.e. casting down the hierarchy.
优先级顺序决定了在表达式中运算符的求值顺序。结合性决定了一个表达式从左向右求值还是从右向左求值。
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left.
一个受保护方法只能由相同包中的类或接口或声明它所在类的子类访问。
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
当一个类在另一个类的范围内定义时,那么它就变成了内部类。如果内部类的访问修饰符是静态的,那么它就变成了嵌套类。
When a class is defined within a scope of another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class.
重写方法必须名称、参数表、返回值类型相同。重写方法不能限制重写方法的访问权限。
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.
一个子对象构造函数总是需要先构造它的父级。在 Java 中它通过一个隐式调用无参数构造函数作为第一个语句来实现。
A child object constructor always first needs to construct its parent. In Java it is done via an implicit call to the no-args constructor as the first statement.
是的,一个 double 值可以强制转换成一个 byte 类型。
Yes, a double value can be cast to a byte.
当异常在 try 语句块内被抛出时,try 语句块中的 catch 块将按照它们出现的顺序被检查。第一个能处理这个异常的 catch 块将被执行。剩下的 catch 块将被忽略。
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.
如果数组是一个原始类型的数组,那么数组的所有元素将被初始化为该原始类型对应的默认值。
If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type.