Exception and thread interview questions that you must master if you want to enter a big Java factory

What is the difference between errors and exceptions?

Errors are unrecoverable conditions that occur at runtime. Such as OutOfMemory error. These JVM errors cannot be fixed at runtime. Although errors can be caught in the catch block, the execution of the application will stop and cannot be recovered.

An exception is a situation that occurs due to input errors or human errors. For example, if the specified file does not exist, FileNotFoundException will be thrown. Otherwise, if you try to use a null reference, a NullPointerException will occur. In most cases, it is possible to recover from the exception (perhaps by providing feedback to the user to enter the correct value, etc.).

How to deal with Java exceptions?

There are five keywords in Java for handling exceptions:

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

Due to time constraints, it is not written in detail, and some may be omitted. Friends who need the full version can click the link below to get it for free

Link: 1103806531 Password: CSDN

What is the difference between Checked Exception and Unchecked Exception?

Check abnormal

  • The classes that extend the Throwable class (except RuntimeException and Error) are called checked exceptions
  • The checked exception is checked at compile time
  • Examples: IOException, SQLException, etc.

Unchecked exception

  • Classes that extend RuntimeException are called unchecked exceptions
  • Unchecked exceptions will not be checked at compile time
  • For example: ArithmeticException, NullPointerException, etc.

What is the purpose of the keywords final, finally and finalize?

final

Final is used to impose restrictions on classes, methods and variables. The final class cannot be inherited, the final method cannot be overridden, and the final variable value cannot be changed. Let us look at the following example to understand it better.

class FinalVarExample {
    
    
    public static void main( String args[]){
    
    
        final int a=10;   // Final variable
        a=50;             //Error as value can't be changed
    }
}

finally

Finally, it is used to place important code, which will be executed regardless of whether the exception is handled. Let us look at the following example to understand it better.

class FinallyExample {
    
    
    public static void main(String args[]){
    
    
        try {
    
    
        	int x=100;
        }catch(Exception e) {
    
    
        	System.out.println(e);
        }finally {
    
    
        	System.out.println("finally block is executing");
        }
    }
}

finalize

Finalize is used to perform cleanup processing before garbage collection. Let us look at the following example to understand it better.

class FinalizeExample {
    
    
    public void finalize() {
    
    
    	System.out.println("Finalize is called");
    }
    public static void main(String args[]){
    
    
        FinalizeExample f1=new FinalizeExample();
        FinalizeExample f2=new FinalizeExample();
        f1= NULL;
        f2=NULL;
        System.gc();
    }
}

What is the exception hierarchy in Java?

Throwable is the parent class of all Exception classes.

There are two types of exceptions: checked exceptions and UncheckedExceptions or RunTimeExceptions. Both types of exceptions extend the Exception class, and errors are further divided into virtual machine errors and assertion errors.

How to create a custom exception?

To create your own exception, extend the Exception class or any of its subclasses.

  • class New1Exception extends Exception {} //This will create Checked Exception
  • Class NewException extends IOException {} //This will create a Checked exception
  • Class NewException extends NullPonterExcpetion {} //This will create an UnChecked exception

What are the important methods of Java exception classes?

The exception and all its subclasses do not provide any specific methods, and all methods are defined in the base class Throwable.

  1. String getMessage() – This method returns the Throwable message string and can provide the message when creating an exception through its constructor.
  2. String getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale-specific messages to the caller. The throwable class implementation of this method only uses the getMessage() method to return an exception message.
  3. Synchronized Throwable getCause()-This method returns the reason for the exception, or returns a null id, the reason is unknown.
  4. String toString()-This method returns information about Throwable in String format. The returned String contains the name of the Throwable class and localized information.
  5. void printStackTrace()-This method prints the stack trace information to the standard error stream. This method has been overloaded. We can pass PrintStream or PrintWriter as a parameter to write the stack trace information to a file or stream.

What is a finally block? Are there any circumstances under which it will not be executed eventually?

The final block is a block that always executes a set of statements. It is always associated with the try block, regardless of whether any exception occurs.
Yes, if the program exits by calling System.exit() or causing a fatal error (causing the process to abort), it will not be executed eventually.

What is synchronization?

Synchronization refers to multiple threads. Synchronized code blocks can only be executed by one thread at a time. Since Java supports multiple threads of execution, two or more threads can access the same field or object. Synchronization is the process of keeping all concurrent threads synchronized during execution. Synchronization avoids memory consistency errors caused by inconsistent views of shared memory. When a method is declared as synchronized, the thread will maintain a monitor of the method object. If another thread is executing the synchronization method, the thread will be blocked until the thread releases the monitor.

Insert picture description here

What are the two ways to create threads?

In Java, threads can be created in the following two ways:

  • By implementing the Runnable interface
  • By extending threads

What are the different types of garbage collectors in Java?

The garbage collector in Java can help with implicit memory management. Since in Java, you can use the new keyword to dynamically create an object, once the object is created, the object will consume some memory. Once the work is completed and there are no more references to the object, Java using garbage collection will destroy the object and release the memory it occupied.

Java provides four types of garbage collectors:

  • Serial garbage collector
  • Parallel garbage collector
  • CMS garbage collector
  • G1 garbage collector

At last

I have also compiled a complete set of video tutorials for architects and systematic materials on java, including java core knowledge points, interview topics, and the latest 20 years of Internet real questions and e-books. Friends in need can click the link below to get it for free!

Link: 1103806531 Password: CSDN

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/XingXing_Java/article/details/109169057