[Interview with experts] - Java basics (36 questions)

Article directory

1. Classification of eight basic data types

(1) The first type of integer type: byte, short, int, long
(2) The second type of floating point type: float, double
(3) The third type of logical type: boolean
(4) The fourth type of character type: char

2. The difference between rewriting and overloading

1. Overloading rules:

①Must have different parameter lists.

②There can be different access modifiers.

③ Different exceptions can be thrown.

2. Rules for overriding methods:

①The parameter list must be exactly the same as the overridden method, otherwise it cannot be called overwriting but overloading.

②The returned type must always be the same as the return type of the overridden method, otherwise it cannot be called overwriting but overloading.

③The access modifier limit must be greater than the access modifier of the overridden method.

④The exception type thrown by the overridden method of the subclass is not greater than the exception type thrown by the overridden method of the parent class.

3. Differences in class relationships:

Overriding is the relationship between subclasses and parent classes, which is a vertical relationship; overloading is the relationship between methods in the same class, which is a horizontal relationship.

3. The difference between int and integer

  • Data type: int is the basic data type of java, integer is the wrapper class of int
  • Nullability: It is a basic data type that cannot represent null. If an int variable is not explicitly initialized, it is assigned a default value of 0. Integer is an object that can represent null values. You can set an Integer to null, meaning it has no value.
  • Performance: int takes up less space in memory because it is a basic data type and does not require an object header and additional storage space. Integer is an object, so it takes up more memory space, and requires additional operations when boxing (converting int to Integer) and unboxing (converting Integer to int), which may affect performance .
  • Methods and operations: int has no methods or properties and can only perform basic mathematical and comparison operations. The Integer class has rich methods, such as: equals, Compareto, toStringwhich can perform various integer-related operations, such as conversion to string, comparison, parsing, etc.

4. Java keywords

(1) Access modifiers (3)
Insert image description here(2) Modify methods, classes, attributes and variables (9)
Insert image description here
(3) Define classes, interfaces, abstract classes and implementation interfaces, keywords of inherited classes, and 6 instantiated objects
Insert image description here
(4) ) 2 keywords of package
Insert image description here
(5) 12 keywords of data type
Insert image description here
(6) Conditional loop (12 in total)
Insert image description here
(7) 5 error handling
Insert image description here
Summary: There are 51
keywords in java + 2 reserved There are 53 keywords in total , and the keywords are all lowercase! Reserved keywords:

  • const
  • goto
    question: But in the process of doing the questions, true, false, and null are not keywords of java. In other words, there are only 50 keywords of java?
    True, false, and null in Java are not keywords or reserved words in Java. They only display constant values, but they cannot be used as identifiers in Java.

5. What is autoboxing and unboxing?

  • Boxing: Basic types are converted into encapsulated types. This process is performed automatically without explicit code.
  • Unboxing: The process of converting encapsulated types into basic types. , this process is also performed automatically.
    Function: Automatic boxing and unboxing make it more convenient to convert between basic data types and packed types, while reducing code redundancy.

6. What is polymorphism in Java?

In layman's terms: it is a variety of forms, specifically to complete a certain behavior. When different objects complete it, different states will be produced!

For example, student is a parent class, then students taking physical education classes on the playground and students in the classroom are its subclasses. At this time, the class bell rang. The students in the physical education class went to the playground, while the students in the classroom returned to the classroom. Different students had different reactions. This is polymorphism.

Role: Flexibility and maintainability, code reuse, multiple implementations of interfaces:

7. What is the difference between interface and abstract class?

The defined keywords are different: interface, abstract class: abstract.
Subclass inheritance or implementation keywords are different: interface: implement, extends.
Type extensions are different: abstract classes have single inheritance, while interfaces have multiple inheritance.
Method access control characters: There are no restrictions on abstract classes, but abstract methods in abstract classes cannot be modified by private; interfaces have restrictions, and the default interface control character is public.
Attribute method control symbols: There are no restrictions on abstract classes, but there are restrictions on interfaces. The default control symbol for interfaces is public.
Method implementations are different: ordinary methods in abstract classes must be implemented, and abstract methods must not be implemented; while ordinary methods in interfaces cannot be implemented, but static and defualt methods in JDK 8 must be implemented.
The use of static code blocks is different: abstract classes can have static code blocks, but interfaces cannot.

8. How to handle exceptions in Java?

Use try…catch

9. What is the function of final keyword in Java?

Structures that final can be used to modify: classes, methods, variables
final is used to modify a class: this class cannot be inherited by other classes.
final is used to modify methods: indicating that this method cannot be overridden.
final is used to modify variables, in which case the variables are equivalent to constants.

10. What is serialization and deserialization in Java?

Serialization is the process of converting an object's state into a stream of bytes so that it can be transmitted over a network or persisted to disk. Deserialization is the process of restoring a serialized byte stream into an object. In Java, serialization and deserialization are implemented through ObjectInputStream and ObjectOutputStream.

Why do we need serialization?

In modern applications, the state of objects often needs to be transferred between different systems, processes, and threads. For example, in a distributed system, objects may need to be transferred between different servers. Another example is when storing objects in cache, the objects need to be serialized so that they can be saved to disk.

11. What are the differences between String, StringBuilder and StringBuffer in Java?

String declares an immutable object. Each operation will generate a new String object, and the pointer will point to the new object.

StringBuffer and StringBuilder can operate on the basis of the original objects.
The difference between StringBuffer and StringBuiler is that StringBuffer is thread-safe and StringBuilder is non-thread-safe.

StringBuilder >StringBuffer > String
But StringBuiler is more efficient than StringBuffer.

12. What are the four major characteristics of object-oriented programming in Java?

Encapsulation, inheritance, polymorphism and abstraction are the four major characteristics of object-oriented programming.

13. What are the functions of equals() and hashCode() methods in Java?

The equals() method is used to compare whether the contents of objects are equal, while the hashCode() method is used to generate a hash code for the object for efficient search and comparison operations in data structures such as collection classes (such as HashMap, HashSet). These two methods generally require consistency, i.e. if two objects are logically equal, their hash codes should also be equal to ensure correct set operation.

14. How to reverse a string?

Use the reverse() method of StringBuilder or stringBuffer.

15. What is the difference between “==” and “equal()” methods?

equals() compares whether the values ​​(contents) of two objects are the same.
"==" compares whether the references (memory addresses) of two objects are the same, and is also used to compare whether the variable values ​​of two basic data types are equal.

16. What is the difference between final, finally and finalize?

  1. Final is used to declare variables, methods and classes, which represent constants respectively. Methods cannot be overridden and classes cannot be inherited.
  2. Finally is part of the exception handling statement structure, indicating a section of code that will always be executed regardless of whether it occurs or not.
    3.finalize is a method in the Object class. When the garbage collector is executed, the finalize() method of the recycled object will be called to perform other resource recycling operations during garbage collection, such as closing files and releasing connections.

17. What is the function of intern() method in String?

If the string constant pool already contains a string equal to this String object, return the reference (memory address) of the string in the constant pool, otherwise put the new string into the constant pool and return the new string's reference(memory address).

18. What are JVM, JRE, JDK?

JVM
JVM. It is the abbreviation of Java Virtual Machine, used to run Java bytecode files (*.class files). JVM has specific implementations for different operating systems (such as Windows, Linux, nacOC). The purpose is to use the same bytecode and run the same results on different operating systems. This is the core mechanism for Java to achieve cross-platform. The default virtual machine in Java is HotSpot VM. In addition, there are virtual machines such as JRockit (BEA), j9 (IBM), TaoBaoVM (Taobao); JRE JRE
stands
for Java Runtime Environment. JRE includes the Java virtual machine and the core class libraries needed by Java programs. If you want to run a developed Java program, you only need to install JRE on your computer.
JDK
JDK is the abbreviation of Java Development Kit (Java Development Kit), which is provided to Java developers. JDK contains JRE and tools for developing, adjusting and monitoring applications, compilation tools (javac.exe), packaging tools ( jar.exe), Java monitoring and management platform (jConsole, jvisualvm), etc.,

JDK contains JRE, and JRE contains JVM. So JDK > JRE > JVM.

19.What are the advantages of Java language?

1. Object-oriented (encapsulation, inheritance, polymorphism);
2. Cross-platform (Java virtual machine achieves platform independence);
3. Reliability;
4. Security;
5. Supports multi-threading;
6. Supports network programming;
7. The execution method adopts the coexistence of interpretation execution + compilation execution;
8. There are many practical application cases.

20.What is a constructor method?

The name of the constructor is consistent with the name of the class;
the constructor does not have a return value type structure, and the constructor cannot be declared with void;
when creating an object, use the new keyword to call the execution constructor;
even if a class does not declare a constructor, Java will provide a default No-argument construction method.

21.What are the common methods in the String class?

  1. indexOf(): Returns the index of the specified character.
  2. charAt(): Returns the character at the specified index.
  3. replace(): string replacement.
  4. substring(): intercept the string.
  5. split(): Split the string and return a split string array.
  6. trim(): removes whitespace at both ends of the string.
  7. getBytes(): Returns a byte type array of string.
  8. length(): Returns the length of the string.
  9. toLowerCase()/toUpperCase(): Convert strings to lowercase/uppercase letters.
  10. equals(): String comparison.

22. Why is hashCode() necessary? (Take "How to check duplicates in HashSet" as an example to illustrate why hashCode is necessary)

1. When you add an object to a HashSet, the HashSet will first obtain the hashCode value of the object to calculate the position where the object is added, and compare it with the hashcode values ​​of other objects that have been added.
2. If there is no duplicate hashCode, HashSet will assume that the object does not appear repeatedly and add it normally.
3. If objects with the same hashCode value are found, the equals() method will be used to check whether the objects with equal hashCode are really the same.
4. If the two are the same, the HashSet will not be added successfully.
5. If the two are different, they will be rehashed to other locations.
6. This greatly reduces the number of executions of equals() and accordingly increases the execution speed.

23 Why must the hahsCode() method be overridden when overriding equals()?

Because there is a certain cooperative relationship between the equals() method and the hashCode() method, they work together to ensure the correct behavior of the object when placed in a data structure such as a hash table.
In order to ensure consistency and performance when using data structures such as hash tables, it is generally recommended to override the hashCode() method when overriding the equals() method, and ensure logical consistency between them. Failure to do so may result in incorrect behavior of objects in the collection and performance issues.

The relationship between equals() method and hashCode() method should be consistent.

  1. If two objects are the same (that is, comparison with equals returns true), then their hashCode values ​​must be the same.
  2. If two objects have the same hashCode, they are not necessarily the same (use equals to compare).

Collaboration relationship: In a hash table (such as HashMap, HashSet), the object's hashCode value is used to determine the storage location of the object in the table, and the equals method is used to check whether two objects are equal. If two objects are considered equal (that is, the equals method returns true), then their hashCode values ​​should be the same.

Performance: If you do not implement the hashCode() method correctly, the performance of the hash table may be affected. In a hash table, the speed of fast search and insertion depends on the hashCode of the object. If the hashCode method is inappropriate, it may cause hash conflicts and reduce the performance of the hash table.

Consistency: According to the Java specification, if two objects are considered equal in the equals() method, their hashCode values ​​must be the same. This is because in the hash table, potential matches are first looked up based on the hashCode value, and then the equals method is used to ensure the accuracy of the match.

To sum up, in every class that overrides the equals() method, the hashCode() method must also be overridden. Failure to do so will violate the general convention of Object.hashCode, resulting in collections such as HashSet and HashTable. In addition, it can avoid equals() being called frequently and reduce performance overhead.

24.What is the role of constant pool technology in package classes?

  1. Byte, Short, Integer, Long create cache data in the range [-128, 127].
    2.Character creates buffer data in the range [0, 127].
    3. If the data is in the cache range, there is no need to re-create the object and it is obtained directly from the cache, reducing the memory and performance overhead caused by repeated object creation.
    4. If the data exceeds the cache range, a new object will be created.

25.What is the string constant pool?

The string constant pool ensures that strings with the same content are only stored once. This means that if two strings have the same sequence of characters (same content), they will reference the same string object.
If you create a String object through new, it will be a new object.

Using the intern() method: The String class provides an intern() method that can be used to explicitly add string objects to the string constant pool. If you need to ensure that the string object exists in the constant pool, you can use this method.

String str1 = "hello"; // 创建一个字符串对象,存储在常量池中
String str2 = "hello"; // 直接引用常量池中的同一字符串对象

String str3 = new String("hello"); // 创建一个新的字符串对象,存储在堆内存中
String str4 = str3.intern(); // 使用intern()方法将字符串对象添加到常量池中

System.out.println(str1 == str2); // true,引用同一常量池对象
System.out.println(str1 == str3); // false,不同对象
System.out.println(str1 == str4); // true,引用同一常量池对象

26.Is Java passed by value or by reference?

In Java, all methods are passed by value. If the parameter is a basic type, the value of the parameter is copied and passed to the method. If the parameter is a reference type, copy the memory address value in the Heap heap of the object parameter and pass it to the method.

27. What are the common methods in the Object class?

  • getClass method: Get the runtime class object of the object. The class object is the object that describes the class to which the object belongs.
  • hashCode method: This method is mainly used to obtain the hash value of an object. This method in Object returns the heap memory address of the object by default.
  • clone method
  • toString method
  • finalize method
  • wait method
  • notify method

28. What are the common interfaces in Java?

1. Collection framework: Collection interface, List interface, Set interface, Map interface;
2. Comparator: Comparator interface, Comparable interface;
3. IO operation: Closeable interface (file stream that can be closed);
4. Marking interface: RandomAccess interface (Random access to collection elements), Serializable interface (serialization), Cloneable interface (object cloning);
5. Thread interface: Runnable interface.

29. What is an exception?

Errors in a program are collectively called exceptions.

30. How do you understand the exception system in Java?

  • Throwable is the parent class of all exception classes;
    • Error The program cannot handle, such as memory overflow, JVM exception
    • Exception program can handle.
    • Checkable exceptions: The most typical ones are IO exceptions. Either use a try-catch statement to capture it, or use a throws clause to declare it, otherwise the compilation will not pass.
    • Uncheckable exception:
      • Runtime exceptions are caught using try…catch
      • Compilation fails due to non-runtime exceptions.

31.What is the difference between Error and Exception?

  1. Error type errors are usually virtual machine-related errors, such as system crash, insufficient memory, stack overflow, etc. The compiler will not detect such errors, and JAVA applications should not capture such errors. Once such errors occur, , the application is usually terminated and cannot be recovered by the application itself;
  2. Exception type exceptions can be caught and handled in the application. Usually when such an error is encountered, it should be handled so that the application can continue to run normally.

32.What is the difference between throw and throws?

  • The throw keyword is used to throw exception objects in methods or code blocks. Both checked exceptions and unchecked exceptions can be thrown and used inside methods;
  • The throws keyword is used to identify the list of exception types that can be thrown by this method. When the method is defined, it is defined after the parameter list and before the method body.

33.What are the common exceptions in Java?

  1. NullPointerException Null pointer exception: This exception is caused by calling an uninstantiated null reference;
  2. ClassNotFoundException Class not found exception: This exception will be thrown when loading a non-existent class (such as during reflection) according to the fully qualified name of the class;
  3. NumberFormatException Number formatting exception: When converting a string to a number, this exception will be thrown if the string contains non-numeric content;
  4. IndexOutOfBoundsException Index out-of-bounds exception: This exception will be thrown when the array or string index exceeds the range;
  5. IllegalArgumentException Illegal parameter exception: The incoming parameter is illegal and this exception is thrown;
  6. ClassCastException Type conversion exception: Convert an incompatible Class type and throw this exception;
  7. SQLException SQL exception: This exception will be thrown when a SQL syntax error occurs when operating the database;
  8. IOException read and write exception: This exception will be thrown when an error occurs during IO read and write operations on the file stream;
  9. NoSuchMethodException There is no exception in the method: the calling method cannot be found, this exception is thrown.

34. Tell me about your understanding of memory visibility?

For example, there is a public variable a, three threads, one thread modifies the value of a, and the other two threads may not see the changed value of a. This is a memory visibility problem.
The reason is: In order to improve processing speed, each thread will maintain a local cache of shared variables in the CPU, and all operations of the thread on shared variables will be performed in its own local cache. If thread A changes a shared variable, thread B may not see thread A's modification
. Solution:

  • Use the volatile keyword:
    Declare a variable as volatile, which tells the Java virtual machine to ensure that all threads see the latest value.
    When a thread modifies the value of a volatile variable, the change is immediately written to main memory, and other threads get the latest value from main memory when reading the variable.

  • Use the synchronized keyword:
    Use synchronized blocks to synchronize read and write operations to ensure that only one thread can access shared variables at the same time.
    When a thread acquires the lock and modifies a shared variable, other threads must wait for the thread to release the lock before accessing the variable, thus ensuring visibility.

  • Use tool classes in the java.util.concurrent package:
    Java provides some concurrency tool classes, such as AtomicInteger, CountDownLatch, CyclicBarrier, etc., which can be used to handle multi-thread visibility issues without manually writing synchronization code.
    These utility classes provide atomic operations and synchronization mechanisms to ensure that modifications to shared variables are visible to other threads.

35. Tell me your understanding of the volatile keyword?

volatile is a keyword in Java used to modify variables. Its main role is to ensure visibility and ordering in a multi-threaded environment, which means that when one thread modifies the value of a volatile variable, other threads can immediately see the modification.
The role of volatile keyword:

  • Visibility: In a multi-threaded environment, when one thread modifies the value of a volatile variable, this change is visible to other threads. This means that when one thread modifies a volatile variable, other threads will not read the expired cached value, but will be able to see the latest value.
  • Disable instruction reordering (Ordering): The volatile keyword also prevents the compiler and processor from reordering instructions. This ensures that reads and writes to volatile variables are executed in the order of the code without unexpected instruction reordering.
  • Atomicity is not guaranteed: The volatile keyword only ensures visibility and ordering, but not atomicity. If multiple threads write to the same volatile variable at the same time, a race condition may occur. For scenarios that require atomic operations, synchronized or atomic classes in java.util.concurrent should be used.

Applicable scenarios: volatile is suitable for some simple flag bit or status identification operations, such as signal notification between threads. It is not suitable for complex operations such as accumulation operations.

36. What are the new features of Java 8?

(1) Default methods and static methods of interfaces: Previously, interfaces could only declare methods without implementation. After Java 8, interfaces are allowed to have a default implementation, which must be marked with the default modifier;

default void test(){
    
    }
static void test2(){
    
    }
  • effect:
    • Adding new methods to existing interfaces: Default methods allow adding new methods to existing interfaces without breaking classes that already implement the interface. Before Java 8, if you wanted to add a new method to an interface, all classes that implemented the interface had to provide an implementation of that method, which could lead to breaking existing code.
    • Extensibility of the interface: The default method improves the extensibility of the interface. New methods can be added to the interface without breaking existing implementation classes. This is useful for interface-oriented programming because it allows the interface to evolve gradually without affecting existing code.
    • Lambda expressions and functional programming: The introduction of default methods, along with lambda expressions, makes interfaces easier to use for functional programming. For example, the functional interface in the java.util.function package in the Java standard library uses default methods, which allows you to implement only one or a few abstract methods when using Lambda expressions.

(2) Lambda expression: The most intuitive thing about Lambda is that it makes the code tidier.

     

(3) Functional interface:

  • Comparetor
  • Consumer
  • predicate (assertive interface)
  • Supplier
  • Function (functional interface)

(4) Method reference: It is used to directly access methods or constructors in a class or instance, so that the code will be more readable.
Just use it ::to call the method in the class:

在这里插入代码片

(5) Stream: It allows you to process data collections in a declarative manner.

  • Features:
    • Internal iteration:
    • It can only be traversed once: when the stream traversal is completed, the stream is consumed.
    • Can be processed in parallel:select.stream().parallel()

(6) Optional: To solve the null pointer exception. And it makes the code more concise, using it we don't need to explicitly perform null pointer detection.
Optional + lambda implements comparing strings and finding the longest string

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class OptionalLambdaExample {
    
    

    public static void main(String[] args) {
    
    
        List<String> stringList = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");

        Optional<String> longestString = stringList.stream()
                .reduce((s1, s2) -> s1.length() > s2.length() ? s1 : s2);

        longestString.ifPresent(s -> System.out.println("最长的字符串是: " + s));
    }
}

(7) Date/Time
(8) Duplicate annotations
(9) Extended annotation support
(10) Base64
(11) JavaFx

Guess you like

Origin blog.csdn.net/qq_42785250/article/details/132942929