Skip to main content

Java Core 核心知识点

1. What is wrapper class in Java and Why we need wrapper class?

  • Wrapper classes provide a way to use primitive data types (int, char, short, byte, etc) as objects. Byte, Short, Integer, Long, Float, Double, Character, Boolean 包装类
  • The classes in java.util package handles only objects, so we need wrapper class.
  • The object is needed to support synchronization in multithreading.
  • A wrapper type is Null without assigning, while a primitive type has a default value and is not Null. Like, in a project we insert one row data with some data not filling in. we need to make them null, not the default value of primitive data types, eg. int = 0.

2. What is the difference between HashMap and HashTable?

HashMapHashTable
No method is synchronized.Every method is synchronized.
Multiple threads can operate simultaneously and hence hashmap’s object is not thread-safe. 非线程安全At a time only one thread is allowed to operate the Hashtable’s object. Hence it is thread-safe. 线程安全
Threads are not required to wait and hence relatively performance is high. 性能高It increases the waiting time of the thread and hence performance is low. 性能低
Null is allowed for both key and value.Null is not allowed for both key and value. Otherwise, we will get a null pointer exception.

3. What is String pool in Java and why we need String pool?

  • String Pool in Java is a pool of Strings which is stored in Java Heap Memory. 字符串常量池是 Java Heap 中一块特别的内存区域。
  • If the string is already present in the pool, then instead of creating a new object, old object’s reference is returned. 当字符串已经存在于池内时,返回旧对象的引用而不是创建新对象。
  • String constant pool exists mainly to reduce memory usage and improve the re-use of existing instances in memory. 减少内存使用,提高复用。
String s1 = "ab"; // put into string pool
String s2 = "ab"; // find in string pool
String s3 = new String("ab"); // create a new string object in Heap memory but not in string pool

System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false

4. What is Java Garbage Collection?

  • Garbage collection in Java is the process by which Java programs perform automatic memory management. GC 是 Java 自动内存管理的过程。
  • Garbage collection in java is the process of looking at heap memory, identifying which objects are in use and which are not and deleting the unused objects. An unused object or unreferenced object, is no longer referenced by any part of your program. 是销毁未使用对象,即未被引用对象的过程。
  • Garbage collector is a daemon thread that keeps running in the background, freeing up heap memory by destroying the unreachable objects.
  • To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

5. Garbage Collection Method

The heap space is divided into smaller parts or generations. These are Young Generation, Old or Tenured Generation and Permanent Generation.

  • The Young Generation: is where all new objects are allocated and aged. 所有新对象被分配和标记年龄的地方。
  • The Old Generation: is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. 当 young generation 对象满足年龄的阈值时,会被移动至 old generation.
  • The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here. JVM 根据运行时所使用的类来填充永久代。

6. When does a memory leak happen?

  • 内存泄漏的定义:应用程序不再使用的对象,垃圾收集器却无法删除它们,因为它们正在被引用。
  • Memory leak occurs when programmers create a memory in heap and forget to delete it. And the garbage collector is unable to remove them from memory.

为什么内存泄露发生?

让我们来看看下面的例子,看看为什么发生内存泄漏。在下面的例子中,对象 A 是指对象 B。A 的生命周期(t1 - t4)比 B 的(t2 - t3)长得多,当应用中不再使用 B 时,A 仍然有一个 B 的引用,这样垃圾收集器就不能从内存中删除 B。这就可能会导致内存不足的问题,因为如果 A 同时为更多的对象做同样的事情,那么会有很多像 B 这样的对象没有收集并占用内存空间。

B 也可能拥有一堆其他对象的引用,B 引用的对象也不会被收集。所有这些未使用的对象将消耗宝贵的内存空间。

如何防止内存泄露?

以下是防止内存泄漏的一些快速实用技巧。

  • 注意集合类,如 HashMap、ArrayList 等,因为它们是发现内存泄漏的常见地方。当它们被声明为静态时,它们的生命时间与应用程序的生命时间是相同的。
  • 注意事件监听器和回调。如果一个侦听器被注册了,但是当类不再被使用时,可能会发生内存泄漏。
  • 如果一个类管理自己的内存,程序应该对内存泄漏保持警惕。通常情况下,指向其他对象的成员变量需要为 null 值。

7. What are access modifiers and their scopes in Java?

Access modifiers in Java helps to restrict the scope of a class, constructor, variable, method, or data member.

ModifierDescription
Defaultdeclarations are visible only within the package (package private)
Privatedeclarations are visible within the class only
Protecteddeclarations are visible within the package or all subclasses
Publicdeclarations are visible everywhere

8. What is final key word? (Filed, Method, Class)

  • The final keyword in java is used to restrict the user. You cannot change the value of final variable (It will be constant).
  • Variable: define constant and its value cannot be changed once assigned. 赋值后不可再修改.
  • Method: cannot override it in the subclass. 不能在子类中 override.
  • Class:
    • prevent inheritance, like Integer, String etc. 不可被继承
    • Make class immutable. 不可变
class Playground {
// A static final variable that is not initialized at the time
// It can be initialized only in static block.

// Variable
public static final int n1;
public final int n2 = 0;

static {
n1 = 10;
}

public static void main(String[ ] args) {
// n1 = 10; // error
// n2 = 10; // error

// reference variable: we can change the ref value
final StringBuilder sb = new StringBuilder("Java");
sb.append("Hello");

System.out.println(sb); // JavaHello
System.out.println(n1); // 10

}

// Method: prevent override
public final int add(int a, int b) {
return a + b;
}

// Class
public final class Test {
// 1) prevent inheritance, like Integer, String etc;
// 2) Make class immutable;
}
}

9. What is static keyword? (Filed, Method, Class). When do we usually use it?

  • The static can be: variable (class variable), method (class method), block & nested class.
  • Static Variable:
    • A static variable can be accessed directly by the class name and doesn’t need any object. 静态变量可以直接通过类名访问.
    • Static variables are initialized only once, at the start of the execution.
    • These variables will be initialized first, before the initialization of any instance variables (Object). 静态变量首先被初始化
  • Static Method:
    • we can directly call static method using Class name, eg. Arrays.sort(). 静态方法可以直接通过类名访问.
    • A static method can call only other static methods and can not call a non-static method from it.
    • A static method cannot refer to “this” or “super” keywords in anyway.
    • A static method belongs to the class rather than object of a class.
    • A static method can be invoked without the need for creating an instance of a class.
  • Static Block: Static block gets executed exactly once when the class is first loaded, use static block to initialize the static variables. 静态代码块在类初始化时执行