Summary of Java basic knowledge points Six points of Java language basic issues

1. Is the import statement present in the compiled code?

does not exist!

2. Will wildcard imports slow down the performance of the program?

Won't. The compiler determines which classes are needed and imports only those classes. The import statement has no effect on the runtime efficiency of the class. Whether to use wildcard imports is a personal preference.

3. What is the difference between the short data type and the char data type?

Both are closely related in that they are both 16 bits in size. The main difference is that short is signed (can store positive and negative numbers), while char is unsigned and can only store positive numbers including 0.

4. Does the enhanced for loop work with iterators?

Not applicable, only for arrays and collections. The reason it doesn't support iterators is because the enhanced for loop itself was added to avoid looping collections with iterators. Read  JSR-201  and the enhanced loop specification draft for more information.

5. Why is the finalize() method deprecated in Java?

The finalize() method is not guaranteed to be called by the JVM. It depends on the JVM implementation. The finalize() method can introduce a bottleneck and reduce performance.

6. How is the CopyOnWrite class different from other concurrent classes such as ConcurrentHashMap?

These classes create a copy of the collection whenever a reference is added, removed, or changed in the collection, and then update the original collection reference to point to the copy. These classes are typically used to ensure that modifications to a collection are not seen by iterators.

7. What is the difference between strip() and trim() methods in String class?

Both methods are used to remove spaces from the beginning and end of a string. trim() only supports ASCII characters, while the strip() method was introduced in Java 11, which supports Unicode and everything.

8. What is an instance initializer?

An instance initializer is a block of code in a class that can be used to initialize its members. It is called every time an object of the class is created and before the constructor is called.

class Animal {
    int legs;

    {
        this.legs = 10;
        System.out.println("Instance initializer block");
    } // This block is called as an instance initializer.

    public Animal() {
        System.out.println("Constructor");
    }
}

        output

Instance initializer block
Constructor

9. What is the real use of "instance initializer block" when we can initialize instance variables in constructor?

  • In classes with multiple constructors, code must be repeated in each constructor. With instance initializers, you only have to write the code once and it will be executed no matter what constructor is used to create the object.
  • Instance initializers are also useful in anonymous inner classes, which cannot declare any constructors at all.

10. What does the fillInStackTrace() method do in a throwable class?

        The fillInStackTrace() method resets the stack trace information in the throwable object and starts a new stack trace with the current method information.

Example without fillinStackTrace()

void methodOne() throws Throwable {
    methodTwo();
}

void methodTwo() throws Throwable {
    methodThree();
}

void methodThree() throws Throwable {
    throw new Exception("Error occurred");
}

public static void main(String[] args) {
    try {
        new Test().methodOne();
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

        output

java.lang.Exception: Error occurred
 at com.test.Test.methodThree(Test.java:14)
 at com.test.Test.methodTwo(Test.java:10)
 at com.test.Test.methodOne(Test.java:6)
 at com.test.Test.main(Test.java:19)

Example using fillInStackTrace()

void methodOne() throws Throwable {
    try {
        methodTwo();
    } catch (Throwable e) {
        throw e.fillInStackTrace();
    }
}

void methodTwo() throws Throwable {
    methodThree();
}

void methodThree() throws Throwable {
    throw new Exception("Error occurred");
}

public static void main(String[] args) {
    try {
        new Test().methodOne();
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

        output

java.lang.Exception: Error occurred
 at com.test.Test.methodOne(Test.java:9)
 at com.test.Test.main(Test.java:23)

11. What is string deduplication?

        String deduplication helps us save memory occupied by repeated string objects in Java applications. It reduces the memory footprint of string objects in Java heap memory by enabling duplicate or identical string values ​​to share the same character array.

12. Can you use the "super" keyword to call a static method of an interface in an implemented class?

        can't compile

interface A {
    public static void print() {
        System.out.println("Hello World");
    }
}

class MyClass implements A {

    public void hello() {
        super.print(); // COMPILATION ERROR!!!
    }
}

        However, you can use the "super" keyword to call a static method of a class in an inherited class.

class A {
    public static void print() {
        System.out.println("Hello World");
    }
}

class MyClass extends A {

    public void hello() {
        super.print(); // Valid!
    }
}

13. Can you create an anonymous class from a final class?

        cannot! Creating an anonymous class is the same as inheriting a class. So while we can't inherit from a "final" class, we can't create an anonymous class either.

final class Bird {
    
}

class MyClass {

    public static void main(String[] args) {
        Bird b = new Bird() {}; // 这句话编译错误

}

14. Does the switch statement accept null values?

        If a null value is passed to the switch statement, it throws a NullPointerException.

15. Can an enum have a public constructor?

        Only private constructors are allowed in enums.

16. What is the difference between exception and error?

        java.lang.Error  represents an error that cannot normally be handled. They usually refer to catastrophic failures, such as exhaustion of system resources. Some examples are java.lang.OutOfMemoryError, java.lang.NoClassDefFoundError and java.lang.UnSupportedClassVersionError

        On the other hand, java.lang.Exception represents errors that can be caught and handled, such as IOException, ArithmeticException, etc.

17. When does the instance operator produce a compilation error?

  • They cannot check primitives
  • Variables must be instantiated.
  • Objects must be in the same inheritance tree. Otherwise, it won't compile.
class A {
}

class B {
}

class C extends A {
}

class Test {
    public static void main(String[] args) {
        A a = new A();
        System.out.println(a instanceof B); // COMPILATION ERROR
        System.out.println(a instanceof C); // Valid
        System.out.println(a instanceof A); // Valid
        
        C c = new C();
        System.out.println(c instanceof A); // Valid since C extends A
    }
}

18. What is short-circuit calculation?

Short-circuit evaluation enables you to not evaluate the right sides of AND and OR expressions when the overall result can be predicted from the values ​​on the left.

int a = 3, b = 2;
boolean c = false;

c = (a > b && ++b == 3); // c is true,   b is 3
c = (a > b && ++b == 3); // c is false,  b is 3

c = (a > b || ++b == 3); // c is false,  b is 4
c = (a < b || ++b == 3); // c is true,   b is 4

c = (a < b | ++b == 3);  // c is true,   b is 5

19. Can you use both "this()" and "super()" in a constructor?

cannot

class Car extends Vehicle {
    
    public Car() {
        this(20);
        super(10); // COMPILATION ERROR!!!
    }

    public Car(int x) {
        super(x);
    }
}

20. What is the output of the following program?

class Test {

    static int myMethod() {
        try {
            throw new RuntimeException();
        } catch (Exception e) {
            System.out.println("Error");
            return 3;
        } finally {
            return 2;
        }
    }
    
    public static void main(String[] args) {
        System.out.println(myMethod());
    }
}

It prints "Error" first, then 2. Always the final block is executed.

21. Why does the switch statement not support Long, Float, Boolean and Double?

  • Floating point numbers are inaccurate. The switch statement is used to perform an exact match. So it's not always a good idea to do exact matches on floats.
  • Boolean values ​​are not supported as it can be done easily by using  if  statement.
  • Not allowed to be long. Because, the switch statement is implemented using the tableswitch  or lookup switch virtual machine instruction code in the JVM  . They only operate on 32-bit opcodes (integers), while long opcodes are 64-bit (8 bytes).

22. What is WeakHashMap?

WeakHashMap is one of three dedicated map implementations in Java. Its key type is WeakReference, which allows map entries to be garbage collected when their keys are no longer referenced in the program. It helps to implement "registry-like" data structures or simple in-memory cache implementations where entries disappear when their keys are no longer accessible by any thread.

23. What is IdentityHashMap  ?

The Map interface requires  the equals() method  to be used in key comparisons . But  IdentityHashMap  uses  ==  sign to check object equality, instead of calling  equals() method, instead of using hashCode(), it uses  System.identityHashCode() to calculate the hash code.

24. What is ConcurrentHashMap?

ConcurrentHashMap is an enhancement of HashMap as we know that HashMap is not a good choice when dealing with threads in our application as performance wise HashMap is not up to par.

25. What is LinkedHashMap  ?

LinkedHashMap  keeps its elements in insertion order and provides fast access through hashing. Additionally, sorting of elements in LRU (least recently used first) order is supported, as shown below.

LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>(16, 0.75f, true);
linkedHashMap.put(0, "a");
linkedHashMap.put(1, "b");
linkedHashMap.put(2, "c");

System.out.println(linkedHashMap);  // {0=a, 1=b, 2=c}
System.out.println(linkedHashMap);  // {0=a, 1=b, 2=c}

linkedHashMap.get(0);
System.out.println(linkedHashMap); // {1=b, 2=c, 0=a}

26. What is the difference between ConcurrentHashMap and Hashtable?

        Hash tables use a single lock for the entire data. ConcurrentHashMap uses multiple locks at the segment level (16 by default) rather than at the object level (i.e. the entire Map).

        ConcurrentHashMap locking only applies to updates. In the case of retrieval, which allows full concurrency, retrieval reflects the results of the most recently completed update operation. Therefore, while writes are done using locks, reads can happen very quickly.

27. What are the four types of references available in Java?

        Java provides four types of references. They are, StrongReference, WeakReference, SoftReference and PhantomReference.

28. What is the difference between isInstance() method and instanceof operator?

        Both instanceof  operator and  isInstance()  method are used to check the class of an object. But the main difference comes when we want to check the class of an object dynamically. In this case the isInstance() method will work. We can't do that with the instance operator.

29. Can we override static methods?

        Can't.

Guess you like

Origin blog.csdn.net/bashendixie5/article/details/131504310