Collection of Java Interview Questions

by sulong on 2008-12-23 10:25:37

### 1. Simple Principles and Applications of Exception Handling Mechanisms in C++ or Java

When a JAVA program violates the semantic rules of JAVA, the JAVA Virtual Machine (JVM) represents the error as an exception. Violations of semantic rules include two scenarios: one is built-in semantic checks provided by the JAVA class library. For example, an array index out of bounds will trigger an `IndexOutOfBoundsException`, and accessing a null object will cause a `NullPointerException`. The other scenario is that JAVA allows programmers to extend this semantic check; programmers can create their own exceptions and freely choose when to use the `throw` keyword to trigger an exception. All exceptions are subclasses of `java.lang.Throwable`.

---

### 2. Similarities and Differences Between Interfaces in Java and Virtual Classes in C++

Since Java does not support multiple inheritance, but there may be cases where a class or object needs to use methods or properties from several different classes or objects, the existing single inheritance mechanism cannot meet the requirements. Compared with inheritance, interfaces have greater flexibility because they contain no implementation code. When a class implements an interface, it must implement all the methods and properties defined in the interface. By default, all properties in an interface are `public static`, and all methods are `public` by default. A class can implement multiple interfaces.

---

### 3. Advantages and Principles of Garbage Collection, Considering Two Types of Collection Mechanisms

A notable feature of the Java language is the introduction of the garbage collection mechanism, which solves the headache of memory management for C++ programmers. It allows Java programmers to write programs without worrying about memory management. Due to the presence of the garbage collector, objects in Java no longer have the concept of "scope"; only object references have "scope". Garbage collection effectively prevents memory leaks and ensures efficient use of available memory. The garbage collector usually runs as a separate low-level thread and unpredictably clears and recycles objects in the heap memory that are already dead or have been unused for a long time. Programmers cannot call the garbage collector in real-time to collect garbage for a specific object or all objects. There are two types of garbage collection mechanisms: generational copying garbage collection and marking garbage collection, as well as incremental garbage collection.