java basic interview questions

java basic interview questions (2)

1. The difference between Java and javasciprt. [Basic]
A: JavaScript and Java are two different products developed by two companies. Java is a new generation of object-oriented programming language introduced by SUN, which is especially suitable for Internet application development. JavaScript, Netscape's product, was developed to extend the capabilities of Netscape Navigator, an object- and event-driven interpretive language that can be embedded in Web pages, preceded by Live Script. Java was predecessor of the Oak language. The following comparisons are made between the two languages:
1) Object-based and object-oriented: Java is a true object-oriented language, even if you develop simple programs, you must design objects; JavaScript is a scripting language that can be used to make complex network-independent software that interacts with users. It is a programming language based on Object Based and Event Driver. Thus, it provides a very rich set of internal objects for designers to use.
2) Interpretation and compilation: Java source code must be compiled before it can be executed; JavaScript is an interpretive programming language whose source code does not need to be compiled and is interpreted and executed by the browser.
3) Strongly typed variables and weakly typed variables: Java uses strong type variable checking, that is, all variables must be declared before compilation; Variable declarations in JavaScript, with their weak types. That is, variables do not need to be declared before they are used, but the interpreter checks their data types at runtime.
4) Code formats are different.

2. Abnormal Architecture

  • java.lang.Throwable
  •  |-----java.lang.Error:Typically, no specific code is written for processing.
    
  •  |-----java.lang.Exception:Exception handling is possible
    
  •  	|------Compile-time exceptions(checked)
    
  •  			|-----IOException
    
  •  				|-----FileNotFoundException
    
  •  			|-----ClassNotFoundException
    
  •  	|------Runtime Exceptions(unchecked,RuntimeException)
    
  •  			|-----NullPointerException
    
  •  			|-----ArrayIndexOutOfBoundsException
    
  •  			|-----ClassCastException
    
  •  			|-----NumberFormatException
    
  •  			|-----InputMismatchException
    
  •  			|-----ArithmeticException
    

2. View compile-time and run-time exceptions from the program execution process

Compile-time exceptions: Possible exceptions when javac.exe naming is performed
Runtime exceptions: Exceptions that occur when java.exe naming is performed

3. Common types of exceptions, please give examples:

//************************The following are runtime exceptions*****************
	//ArithmeticException
	@Test
	public void test6(){
		int a = 10;
		int b = 0;
		System.out.println(a / b);
	}
	
	//InputMismatchException
	@Test
	public void test5(){
		Scanner scanner = new Scanner(System.in);
		int score = scanner.nextInt();
		System.out.println(score);
		
		scanner.close();
	}
	
	//NumberFormatException
	@Test
	public void test4(){
		
		String str = "123";
		str = "abc";
		int num = Integer.parseInt(str);
		
		
		
	}
	
	//ClassCastException
	@Test
	public void test3(){
		Object obj = new Date();
		String str = (String)obj;
	}
	
	//IndexOutOfBoundsException
	@Test
	public void test2(){
		//ArrayIndexOutOfBoundsException
//		int[] arr = new int[10];
//		System.out.println(arr[10]);
		//StringIndexOutOfBoundsException
		String str = "abc";
		System.out.println(str.charAt(3));
	}
	
	//NullPointerException
	@Test
	public void test1(){
		
//		int[] arr = null;
//		System.out.println(arr[3]);
		
		String str = "abc";
		str = null;
		System.out.println(str.charAt(0));
		
	}

	//**********************The following are compile-time exceptions*******************
	@Test
	public void test7(){
//		File file = new File("hello.txt");
//		FileInputStream fis = new FileInputStream(file);
//		
//		int data = fis.read();
//		while(data != -1){
//			System.out.print((char)data);
//			data = fis.read();
//		}
//		
//		fis.close();
		
	}

3. How do I handle exceptions?
Exception handling method one:
try-catch-finally

Exception handling mode two:
"throws +exception type" is written at the declaration of the method. Indicates the type of exception that may be thrown when this method is executed.
Once an exception occurs when the method body executes, an object of the exception class is generated at the exception code, which is thrown when it satisfies the exception type after throws. Exception code subsequent code, no longer execute!

Comparing Two Processing Methods

try-catch-finally: The exception was actually handled.
throws simply throw exceptions to the caller of the method. The exception was not actually handled.

Experience how to choose two processing methods in development?
1. If the overridden method in the parent class does not handle exceptions in throws mode, then the overridden method in the subclass cannot use throws either, which means that if the overridden method in the subclass is an exception, it must be handled in try-catch-final mode.
2. In method a of execution, several other methods are called, which are executed by a progressive relationship. We recommend that these methods be handled using throws. The execution of method a can be considered using try-catch-finally.

4. If there is a return statement in try {}, will the code in finally {} immediately after this try be executed, when will it be executed, before or after return? [Basic]
A: Yes, before return ing.
However, finally may also change the return value, so this is not recommended.

What is the difference between 5.final, finally, finalize? [Basic]
A: **final:** modifier (keyword); If a class is declared final, it means that it can no longer derive new subclasses or be inherited as a parent, so a class cannot be declared both abstract and final; Declaring variables or methods as final ensures that they remain unchanged in use; Variables declared final must be given an initial value at the time of declaration and can only be read and not modified in subsequent references. Methods declared final can also be used only and cannot be overloaded.

**finally:**Provide a finally block for any cleanup operations when exception handling is resumed; If an exception is thrown, the matching catch clause executes, and the control enters the final block, if any.

**finalize:**method name; Java technology allows the finalize() method to do the necessary cleanup before the garbage collector clears the object out of memory. This method is called by the garbage collector on this object when it is determined that it is not referenced. It is defined in the Object class, so all classes inherit it. Subclasses override finalize() methods to marshal system resources or perform other cleanups. The finalize() method is called on the object before it is deleted by the garbage collector.
6. Common collections

Collection interface: A single-column collection used to store one object by one

List interface: Stores ordered, repeatable data. --> Dynamic Array
ArrayList,LinkedList,Vector
Set interface: Store disordered, non-repeatable data --> Set from High School
HashSet,LinkedHashSet,TreeSet

Map: Two-column data that stores key-value pairs of data - similar to a high school function: y = f(x)

HashMap: As the main implementation class of Map; Threads are insecure and efficient; Store null's key and value
LinkedHashMap: Ensures that the map elements can be traversed in the order they were added.
Reason: A pair of pointers was added to the original HashMap underlying structure to point to the previous and the latter elements.
This type of execution is more efficient than HashMap for frequent traversal operations.
TreeMap: Ensures sorting according to added key-value pairs for sorting traversal. Consider natural or custom key sorting at this point, using red and black trees at the bottom
Hashtable: As an old implementation class; Thread-safe and inefficient; Cannot store null key and value
Properties: Used to process configuration files. Both key and value are String types
At the bottom of HashMap:
Array + Chain List (jdk7 and earlier)
Array + Chain List + Red-Black Tree (jdk 8)
7. Say the storage performance and features of ArrayList,Vector, LinkedList? [Basic]

A: Both ArrayList and Vector use arrays to store data. The number of elements in the array is larger than the actual stored data for adding and inserting elements. Both allow elements to be indexed directly by serial number. However, inserting elements involves memory operations such as moving array elements, so index data is fast and inserting data is slow. Vector uses synchronized method (thread-safe). Usually performance is worse than ArrayList, but LinkedList uses a two-way chain table for storage. Index data by serial number requires forward or backward traversal, but inserting data requires only recording the front and back items of the item, so insertion speed is faster.

8. The difference between Collection and Collections? [Basic]
A: Collection is the interface under java.util. It is the parent interface of various collections, and the interfaces inherited from it are mainly Set and List. Collections is a class under java.util that is a help class for collections and provides a series of static methods to search, sort, thread-safe various collections.
9. The difference between HashMap and Hashtable? [Basic]
A: Both implement the Map interface, mapping the only key to a specific value; The main difference is:
1)HashMap has no sorting, allowing one null key and multiple null values, but Hashtable does not;
2)HashMap removed Hashtable's contains method and changed it to containsvalue and containsKey because the contains method is misleading;
3)Hashtable inherits from the Dictionary class, HashMap is the implementation of the Map interface introduced by Java 1.2;
4) H ashtable's method is Synchronize, but HashMap is not. When accessing H***bold style***ashtable on multiple threads, you don't need to synchronize its method yourself, but HashMap must provide out-of-sync for it. Hashtable and HashMap use roughly the same hash/rehash algorithm, so there is no significant difference in performance.

10. What is the difference between Arraylist and Vector? [Basic]
A: As far as ArrayList and Vector are concerned, there are two main aspects:
1) Synchronization: Vector is thread-safe (synchronization), while ArrayList is thread-insecure;
2) Data growth: Vector doubles by default when growth is needed, while ArrayList is half.

11. List, Map, Set, what are the features of each interface when accessing elements? [Basic]
A: List s hold elements in a specific order and can have duplicate elements. Set cannot have duplicate elements, internal sort. Map holds key-value values, which can be multivalued.

12. Elements in a Set cannot be repeated, so how do you distinguish repetition from non-repetition? Is it==or equals()? What is the difference between them? [Basic]
A: Elements in a Set cannot be duplicated. Use the equals () method to distinguish duplicates from non-duplicates. The override equals() method is used to determine if the contents of the object are the same, and the'**=='method is used to determine if the addresses are equal and whether the reference values point to the same object.

13. Use the program to give 10 numbers of random size, the serial number is 1-10, output in order from small to large, and output the corresponding serial number. [Basic]
A: The code is as follows:

package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class RandomSort {
public static void printRandomBySort() {
Random random = new Random(); // Create Random Number Generator
List list = new ArrayList();
// Generate 10 random numbers and place them in the set list
for (int i = 0; i < 10; i++) {
list.add(random.nextInt(1000));
}
Collections.sort(list); // Sort elements in a collection
Iterator it = list.iterator();
int count = 0;
while (it.hasNext()) { // Ordered Output Elements in Sorted Collection
System.out.println(++count + ": " + it.next());
}
}
public static void main(String[] args) {
printRandomBySort();
}
}

14. Using JAVA to achieve a sort, and using JAVA classes to achieve serialization? What interfaces are implemented for comparison in the COLLECTION framework? [Basic]
A: Sort the code by insertion as follows:

package test;
import java.util.*;
class InsertSort {
ArrayList al;
public InsertSort(int num,int mod) {
al = new ArrayList(num);
Random rand = new Random();
System.out.println("The ArrayList Sort Before:");
for (int i=0;i<num ;i++ ){
al.add(new Integer(Math.abs(rand.nextInt()) % mod +
1));
System.out.println("al["+i+"]="+al.get(i));
}
}
public void SortIt(){
tempInt;
int MaxSize=1;
for(int i=1;i<al.size();i++){
tempInt = (Integer)al.remove(i);
if(tempInt.intValue() >=
((Integer)al.get(MaxSize-1)).intValue()){
al.add(MaxSize,tempInt);
MaxSize++;
System.out.println(al.toString());
}else{
for (int j=0;j<MaxSize ;j++ ){
if (((Integer)al.get(j)).intValue()
>=tempInt.intValue()){
al.add(j,tempInt);
MaxSize++;
System.out.println(al.toString());
break;
}
}
}
}
System.out.println("The ArrayList Sort After:");
for(int i=0;i<al.size();i++){
System.out.println("al["+i+"]="+al.get(i));
}
}
public static void main(String[] args){
InsertSort is = new InsertSort(10,100);
is.SortIt();
}
}

The JAVA class implements ordering by implementing the java.io.Serializable interface. Comparable and Comparator interfaces are implemented in the Collection framework for comparison.

15. What is the difference between sleep() and wait()? [Basic]
A: Sleep is a Thread method that causes this thread to pause execution for a specified time, giving execution opportunities to other threads, but the monitoring status remains and it will automatically resume after that time. Calling sleep does not release object locks. A wait is a method of the Object class. Calling the wait method on this object causes the thread to discard the object lock and enter the wait lock pool waiting for the object. The thread does not enter the object lock pool until the notify method (or notifyAll) is issued against the object, ready to get the object lock into operation.
16. When a thread enters a synchronized method of an object, can other threads enter other methods of the object? [Basic]
Answer: Other threads can only access other asynchronous methods of the object, but synchronous methods cannot enter.
17. Please tell me what thread synchronization method you know. [Basic]
Answer: wait(): Make a thread wait and release the lock on the object it holds; sleep(): To put a running thread to sleep is a static method that is called to catch an InterruptedException exception. notify(): wakes a thread in a waiting state, noting that when this method is called, it is not possible to wake a thread in a waiting state exactly. Instead, the JVM determines which thread to wake up, not by priority;
notityAll(): Wakes up all threads in a waiting state, noting that instead of locking an object for all waking threads, it lets them compete.
18. There are several implementations of multithreading, what are they? [Basic]
A: There are four ways to implement multithreading:
Mode 1: Inherit the Thread class in:

    1. Create a subclass that inherits from the Thread class
    1. Override run() of Thread class --> Declare actions performed by this thread in run()
    1. Objects that create subclasses of the Thread class
    1. Call start() through this object: (1) Start the current thread; (2) Call the run() method of the current thread
package Thread;

/**
 * @description  Create two threads, one that traverses an even number within 100 and the other that traverses an odd number within 100
 * @Author funny
 * @date 2021/11/4-14:54
 */
public class ThreadDemo {
    public static void main(String[] args) {
        MyThread1 myThread1 = new MyThread1();
        MyThread2 myThread2 = new MyThread2();
        myThread1.start();
        myThread2.start();



    }


}
class MyThread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(Thread.currentThread().getName()+":" + i);
            }

        }
    }
}
class MyThread2 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 != 0){
                System.out.println(Thread.currentThread().getName()+":" + i);
            }

        }
    }
}

Mode 2: How to implement the Runnable interface:

    1. Create a class that implements the Runnable interface
    1. Implement classes to implement abstract methods in Runnable: run()
    1. Create objects that implement classes
    1. Pass this object as an argument to the constructor of the Thread class to create an object of the Thread class
    1. Call start() through an object of the Thread class
package Thread;

/**
 * @description
 * @Author funny
 * @date 2021/11/4-20:36
 */
public class ThreadDemoRunnable {
    public static void main(String[] args) {
        Run1 run1 = new Run1();
        Thread thread1 = new Thread(run1);
        Thread thread2 = new Thread(run1);
        thread1.start();
        thread2.start();


    }
}
class Run1 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 ==0){
                System.out.println(Thread.currentThread().getName()+ ":"+ i);
            }

        }
    }
}

A comparison of the two ways:

  • Development: Priority: Ways to implement the Runnable interface
  • Reason: 1. Limitations of implementation without class single inheritance
  •  2. The implementation is more appropriate when multiple threads share data.
    
  • Contact: public class Thread implements Runnable
  • The same point: both methods require rewriting run() to place the logical declaration the thread is going to execute in run().
    In both cases, to start a thread, start() in the calling Thread class is used.

New way 1: Implement Callable interface. JDK 5.0 New

//1. Create an implementation class that implements Callable
class NumThread implements Callable{
    //2. Implement the call method, declaring the operations this thread needs to perform in call()
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}


public class ThreadNew {
    public static void main(String[] args) {
        //3. Create object of Callable interface implementation class
        NumThread numThread = new NumThread();
        //4. Create FutureTask objects by passing objects of this Callable interface implementation class to the FutureTask constructor
        FutureTask futureTask = new FutureTask(numThread);
        //5. Pass the object of FutureTask as an argument to the constructor of the Thread class, create the Thread object, and call start()
        new Thread(futureTask).start();

        try {
            //6. Get the return value of the call method in Callable
            //The return value of get() is the return value of call() whose FutureTask constructor parameter Callable implements a class override.
            Object sum = futureTask.get();
            System.out.println("The sum is:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

Explain:

  • How do you understand that creating multithreads is a more powerful way to implement the Callable interface than implementing the Runnable interface?
    1. call() can return a value.
    1. call() can throw an exception, be caught by an external operation, and get information about the exception
    1. Callable is generic

New way 2: use thread pool

class NumberThread implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i <= 100;i++){
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}

class NumberThread1 implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i <= 100;i++){
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}

public class ThreadPool {

    public static void main(String[] args) {
        //1. Provide a thread pool with a specified number of threads
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //Set Thread Pool Properties
//        System.out.println(service.getClass());
//        service1.setCorePoolSize(15);
//        service1.setKeepAliveTime();


        //2. Perform the operation of the specified thread. An object that implements a Runnable or Callable interface implementation class is required
        service.execute(new NumberThread());//Suitable for Runnable
        service.execute(new NumberThread1());//Suitable for Runnable

//        service.submit(Callable callable);// Suitable for Callable
        //3. Close connection pool
        service.shutdown();
    }

}

Explain:

  • Benefits:
  • 1. Increase response speed (reduces time to create new threads)
  • 2. Reduce resource consumption (reuse threads in the thread pool, do not need to be created every time)
  • 3. Easy thread management
  •  corePoolSize: Core pool size
    
  •  maximumPoolSize: Maximum Threads
    
  •  keepAliveTime: The maximum amount of time a thread can remain unavailable before terminating
    

19. What are the similarities and differences between synchronous and asynchronous, and under what circumstances are they used separately? Examples are given. [Basic]
Answer: If the data will be shared between threads. For example, the data being written may later be read by another thread, or the data being read may have already been written by another thread. The data is shared data and must be accessed synchronously. Asynchronous programming should be used when an application calls a method on an object that takes a long time to execute and does not want the program to wait for the method to return, and in many cases it is often more efficient to use the asynchronous approach.

20. Do you want to start a thread with run() or start()? [Basic]
A: Starting a thread is a call to the start() method to make the virtual processor it represents run, which means it can be scheduled and executed by the JVM. This does not mean that the thread will run immediately. The run() method produces a flag that must exit to stop a thread.

21. Basic concepts of threads, basic state of threads, and the relationship between states? [Basic]
Answer: Threads refer to an executing unit that can execute program code during program execution. Each program has at least one thread, that is, the program itself; Threads in Java have four states: run, ready, suspend, and end.
22. Briefly describe the similarities and differences between synchronized and java.util.concurrent.locks.Lock? [Medium difficulty]
A: The main similarity is that Lock can accomplish all the functions that synchronized implements; The main difference is that Lock has more precise thread semantics and better performance than synchronized. Synchronized automatically releases the lock, and Lock must require the programmer to release it manually and must release it in the final clause.

23. How many ways can a thread be implemented in java? What keyword modifies the synchronization method? Why are the stop() and suspend() methods not recommended? [Medium difficulty]
A: There are two implementations, inheriting the Thread class and implementing the Runnable interface. Modify the synchronized method with the synchronized keyword; Sto() is opposed because it is not safe. It unlocks all locks acquired by threads, and if objects are in a discontinuous state, other threads can examine and modify them in that state. It's hard to find out what the real problem is; The suspend() method is prone to deadlocks. When suspend() is called, the target thread stops, but it still holds the lock it acquired before. At this time, no other thread can access the locked resource unless the suspended thread resumes running. For any thread, a deadlock can occur if they want to restore the target thread while attempting to use any locked resource. Instead of using suspend (), you should place a flag in your Thread class indicating whether the thread should be active or suspended. If the flag indicates that the thread should hang, wait() is used to force it to wait. If the flag indicates that the thread should resume, restart the thread with a notify().

24. What is java serialization and how to achieve it? [Basic]
A: Serialization is a mechanism for dealing with object flow, which means streaming the contents of objects. The streamed objects can be read and written, or they can be transferred between networks. Serialization is designed to solve problems that arise when reading and writing an object stream; Serialization implementation: Classes that need to be serialized implement the Serializable interface, which does not have a method to implement. Implementations Serializable simply means to label that the object is serializable, then construct an ObjectOutputStream object using an output stream such as FileOutputStream, and then use the writeObject of the ObjectOutputStream object The (Object obj) method writes out an object with an obj parameter (that is, saves its state) and uses an input stream to recover it.

25. How many types of streams are there in java? JDK provides abstract classes for each type of stream to inherit. What classes are they? [Basic]
A: Byte stream, character stream. Byte streams inherit from InputStream, OutputStream, and character streams inherit from Reader, Writer. There are many other streams in the java.io package, primarily to improve performance and ease of use.

26. Write a single pattern
Lazy:

package Singleton;

/**
 * @description Single pattern Hungry Han style
 * @Author funny
 * @date 2021/11/9-15:08
 */
public class SingletonHungry {
    private static SingletonHungry instance = new SingletonHungry();
    private SingletonHungry(){

    }
    public static SingletonHungry getInstance(){
        return instance;
    }
}

Hungry Han (thread safe):

package Singleton;

/**
 * @description Lazy (Thread Safe)
 * @Author funny
 * @date 2021/11/9-15:14
 */
public class SingletonLazy {
    private static SingletonLazy instance = null;

    private SingletonLazy() {

    }

    public static SingletonLazy getInstance() {
        if (instance == null) {
            synchronized (SingletonLazy.class) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }

        }
        return instance;
    }
}

Continuous updates are in progress.

Tags: Java Javascript Back-end Interview Singleton pattern

Posted on Sun, 05 Dec 2021 18:48:26 -0500 by bombayduck