Home > Java > javaTutorial > body text

Share some basic Java interview questions

零下一度
Release: 2017-06-23 09:30:43
Original
1389 people have browsed it

1.Where data is saved

Register, stack, heap, static storage, constant storage (constant pool String a = "abc" a is in the stack, "abc" is in the constant pool), non-RAMstorage

2.Basic data Type

As a member of the class, it is automatically initialized to the default value

boolean       1bit Defaultfalse

byte 8bits One byte \u0000

char 16bits One character 0

short 16bits 0

int 32bits 0

float 32bits 0.0f

long 64bits 0L

double 64bits 0.0d

3.High precision number class

BigInteger, Bigdecimal High precision, slow speed

4.javaGarbage processing

Java has a special "garbage collector" that looks for all objects created with new and identifies which of them are no longer referenced . It then automatically frees the memory occupied by those idle objects so that it can be used by new objects.

5.staticExecution order

Parent class static Member variablesand static Statements

static Member variables and# of subclasses ## static Statement

Parent class non- static member variable and are not static Statement block

Construction method of parent class

Non- static member variables and non-static statement blocks of subclasses

Construction method of subclass

(static is only executed once. The first time Executed when new)

6.Collection class

Vector

An array that will grow automatically, with high query efficiency, low addition and deletion efficiency, thread safety, slow speed, and double the original size.

ArrayList

will automatically grow the array, with high query efficiency, low addition and deletion efficiency, thread unsafe, fast speed, and will grow to the original 0.5 times.

LinkedList

Bidirectional circular linked list has low query efficiency, high addition and deletion efficiency, and is thread-unsafe.

HashMap

is a linked list hash, which is a combination of an array and a linked list. It allows null values, is thread-safe and highly efficient.

TreeMap

is implemented for binary sorting tree, using Key for sorting.

LinkedHashMap

is implemented for hash tables and linked lists. It is a subclass of HashMap. It retains the order of insertion. If output is required The order is the same as the input, then use LinkedHashMap.

Hashtable Thread safe, low efficiency, null value is not allowed.

Set is non-repeatable:

TreeSet is implemented based on TreeMap and is ordered Yes, thread-unsafe.

HashSet Based on HashMap implementation, HashMap#key .

LinkedHashSet is implemented based on LinkedHashMap and is ordered.

7. Traversal of Map

##Use entrySet Traversal Map class collection KV, instead of keySet way to traverse.
Explanation: keySet is actually traversed 2 times, and once it is converted to Iterator object, the other time is to take out the value## corresponding to key from
hashMap #. And entrySet only traversed once and put both key and value entry , the efficiency is higher. If it is
JDK8, use the Map.foreach method. Positive example:
values() returns a V value set, which is a list Collection object; keySet() returns the K value set, which is A
Set Set object; entrySet() returns a K-V value combination set.

1, entrySet implements the Set interface, which stores key-value pairs. A K corresponds to a V.
2, a method used to traverse map.
Set> entryseSet=map.entrySet();
for (Map.Entry entry:entryseSet) {
System.out .println(entry.getKey()+","+entry.getValue());
}
GetK## through getKey() #,getValuegetV.
3
, and another one is keySet. Set set = map.keySet();
for (String s:set) {
System.out.println(s+","+map.get(s)) ;
}

2. IOSystem

Bridge stream:

InputStreamReader

Convert byte stream into character stream. (Read as converted into a character stream)

OutputStreamWriter

Convert the character stream into a byte stream (Write as converted into a byte stream)

Access valueAccess pipe (thread interaction)Access string##StringWriter##Processing Stream##Abstract base class (filtering)Print StreamPushback InputStream##Special Stream
Traffic classification

Use classification

Byte input stream

Byte output stream

Character input stream

Character output stream

Abstract base class

InputStream

OutputStream

Reader

Writer

Node Stream

Access File

FileInputStream

FileOutStream

FileReader

##FileWriter

ByteArrayInputStream

ByteArrayOutStream

CharArrayReader

CharArrayWriter

PipedInputStream

PipedOutStream

PipedReader

PipedWriter

StringReader

Buffered Stream

BufferedInputStream

BufferedOutputStream

BufferedReader

BufferedWriter

##Convert stream

InputStreamReader

OutputStreamWriter

Object Stream

ObjectInputStream

ObjectOutputStream

##FilterInputStream

FilterOutputStream

FilterReader

FilterWriter

PrintStream

PrintWriter

PushbackInputStream

PushbackReader

DataInputStream

DataOutputStream

1.Java IO adopts the decoration mode, which uses the processing stream to wrap the node stream to achieve code versatility.

2.How to distinguish between processing flow and node flow. Node flow requires a data source (file, network) as a parameter when creating a new one, while processing flow requires a node flow as a parameter.

3.The function of processing flow is to improve the versatility of code, the convenience of writing code, and improve performance.

4.Node streams are all implementation classes corresponding to the abstract base class, and they all implement the basic reading and writing methods of the abstract base class. Among them, if the read() method returns -1, it means that the end of the data source has been read.

1. Frame diagram of the input stream in bytes

The following is a frame diagram of the input stream in bytes.

From this, we can see.
(01) InputStream is the superclass of input stream in bytes. InputStream Provides the read() interface to read byte data from the input stream.
(02) ByteArrayInputStream is a byte array input stream. It contains an internal buffer that contains the bytes read from the stream; in layman's terms, its internal buffer is a byte array, and ByteArrayInputStreamessentially This is achieved through byte arrays.
(03) PipedInputStream is a pipeline input stream. It is used together with PipedOutputStream to achieve pipeline communication between multiple threads.
(04) FilterInputStream is to filter the input stream. It is the superclass of DataInputStream and BufferedInputStream.
(05) DataInputStream is the data input stream. It is used to decorate other input streams, which "allows applications to read basic Java data types from the underlying input stream in a machine-independent manner."
(06) BufferedInputStream is a buffered input stream. What it does is add buffering functionality to another input stream.
(07) File is an abstract representation of "file" and "directory path name". Regarding File, please note two points:
a), File not only represents a file, it can also represent a directory!
b), FileAlthough it is defined carefully in io, its super class is Object , instead of InputStream.
(08) FileDescriptor is the "file descriptor". It can be used to represent open files, open sockets, etc.
(09) FileInputStream is the file input stream. It is usually used for reading operations on files.
(10) ObjectInputStream is the object input stream. It, together with ObjectOutputStream, is used to provide persistent storage of "basic data or objects".


2. Frame diagram of the output stream in bytes

The following is the frame of the output stream in bytes picture.

From this, we can see. The common parent class for output streams in bytes is OutputStream.
(01) OutputStream is the superclass of the output stream in bytes. OutputStream Provides the write() interface to read byte data from the output stream.
(02) ByteArrayOutputStream is a byte array output stream. Data written to ByteArrayOutputStream is written to a byte array. The buffer will grow automatically as data is continuously written. Data can be obtained using toByteArray() and toString() .
(03) PipedOutputStream is a pipeline output stream. It is used together with PipedInputStream to realize pipeline communication between multiple threads.
(04) FilterOutputStream is the filter output stream. It is a superclass of DataOutputStream, BufferedOutputStream, and PrintStream.
(05) DataOutputStream is the data output stream. It is used to decorate other output streams, which "allows applications to write to the underlying Java data types in a machine-independent manner."
(06) BufferedOutputStream is a buffered output stream. What it does is add buffering functionality to another output stream.
(07) PrintStream is the print output stream. It is used to decorate other output streams and add functionality to other output streams so that they can easily print various data value representations.
(08) FileOutputStream is the file output stream. It is typically used for writing to files.
(09) ObjectOutputStream is the object output stream. It, together with ObjectInputStream, is used to provide persistent storage of "basic data or objects".

3. Multi-threading

Life cycle

Threads include the following 5 states.
1. New state(New): After the thread object is created, it enters the new state. For example, Thread thread = new Thread().
2. Ready state(Runnable): Also known as "executable state". After the thread object is created, other threads call the start() method of the object to start the thread. For example, thread.start(). Threads in the ready state may be scheduled for execution by CPU at any time.
3. Running status(Running): The thread obtains CPU permission to execute. It should be noted that a thread can only enter the running state from the ready state.
4. Blocked state(Blocked) : The blocked state is when the thread gives up for some reasonCPURight to use, temporarily stopped running. Until the thread enters the ready state, it has a chance to move to the running state. There are three blocking situations:
(01) Waiting for blocking-- By calling the thread's wait()Method to let the thread wait for the completion of a certain job.
(02) Synchronization blocking-- The thread failed to acquire the synchronizedsynchronization lock (Because the lock is occupied by other threads), it will enter the synchronous blocking state.
(03) Other blocking-- By calling the thread's sleep() or ## When #join() or an I/O request is issued, the thread will enter the blocking state. When sleep() status times out, join() waits for the thread to terminate or times out, or I/O When the processing is completed, the thread returns to the ready state. 5.
Death state(Dead) : The thread has finished executing or exited due to an exceptionrun()Method, the thread ends its life cycle.

2.

start() and run() Description of the difference

//

InheritanceThread

class MyThread extends Thread{

public void run(){

...

}

};

MyThread mythread = new MyThread();

//

implementationRunnable

class MyThread implements Runnable{

public void run(){

...

}

};

MyThread mt=new MyThread( );

Thread t1=new Thread(mt);

mythread.start() will start a new thread and run the run() method in the new thread.
And mythread.run() will run the run() method directly in the current thread and will not start A new thread to run run().

3.synchronized

We summarize the basic rules of synchronized as follows3 articles and illustrate them with examples.
First Article: When a thread accesses "Some object""synchronizedmethod"or"synchronizedcode block ", other threads are interested in "this object"'s "synchronizedmethod"or"synchronizedcode block" Access to will be blocked.
Second Article: When a thread accesses "Some object""synchronizedmethod"or"synchronizedcode block ", other threads can still access the asynchronous code block of "this object" .
Article 3: When a thread accesses "Some object""synchronizedmethod"or"synchronizedcode block ", other threads "this object"'s other "synchronizedmethod"or"synchronizedcode block"## Access to # will be blocked.

4.wait(), notify(), notifyAll()

notify()-- Wake up and wait on this object monitor of a single thread.
notifyAll()-- Wake up all threads waiting on this object monitor.
wait()-- Let the current thread be in "Waiting(Blocking)State","until other threads call this object's notify() method or notifyAll() method, the current thread is awakened(Enter"Ready state").
wait(long timeout)-- Let the current thread be in "Waiting(Blocking)State","until other threads call this object's notify() method or notifyAll() method, or the specified amount of time , The current thread is awakened(Enter"Ready state").
wait(long timeout, int nanos)-- Let the current thread be in wait( Blocking)State"," until another thread calls this object's notify() method or notifyAll() method, or some other thread interrupts the current thread, or a certain actual amount of time has elapsed ", the current thread is awakened(enters "ready state ”).

5.yield()Introduction

yield()’s function is to yield. It allows the current thread to enter from "Running state" to "Ready Status , thereby allowing other waiting threads with the same priority to obtain execution rights; however, there is no guarantee that yield() will be called on the current thread. After that, other threads with the same priority will definitely be able to obtain execution rights; it is also possible that the current thread has entered "Running state"Keep running!

6.sleep()Introduction

sleep() Defined in Thread.java middle.
sleep() The function is to make the current thread sleep, that is, the current thread will enter from "Running state" ##"Hibernate(Blocking)State". sleep() will specify the sleep time, and the thread sleep time will be greater than / equal to the sleep time; when the thread is awakened again , it will change from "Blocking State" to "Ready State" , thus waiting for the scheduled execution of cpu.

We know that the function of wait() is to make the current thread change from "Running stateEnterWaiting(Blocking)State, the synchronization lock will also be released. The function of sleep() is also to make the current thread change from "Running state"Enter"sleep(blocking)state.
However, wait() will release the synchronization lock of the object, while sleep() will not release the lock.
The following example demonstrates that sleep() will not release the lock.

We know that the function of wait() is to make the current thread enter ## from "Running state" #"Waiting(Blocking)Status" At the same time, the synchronization lock will also be released. The function of yield() is to give way, it will also make the current thread leave "Running state" . The difference between them is: (01) wait()
Let the thread change from "Running state"Enter "Waiting(Blocking)State, and yield() causes the thread to change from to the running stateEnter Ready state. (02) wait()
will cause the thread to release the synchronization lock of the object it holds, but the yield() method will not release the lock.

7.

join()Introduction

join()

Defined in Thread.java middle. join()
Function: Let"main thread"wait"child thread" can only continue to run after it ends. This sentence may be a bit obscure, but we still understand it through examples:

//

Main threadpublic class Father extends Thread {

public void run() {

Son s = new Son();

s.start();

s.join();

        ...

       }

}//

Son threadpublic class Son extends Thread {

     public void run( ) {

...

}

}

Its source code is that when the child thread is alive (isAlive()), the main thread will not Stop waiting (wait(0))

8.

interrupt() and the way to terminate the thread

interrupt()

The function is to interrupt this thread. This thread is allowed to interrupt itself; when other threads call this thread's interrupt() method, they will pass checkAccess() Check permissions. This may throw a SecurityException exception.

If this thread is in a blocked state: call the thread's wait(), wait(long) or wait(long, int) It will enter the waiting (blocking) state, or call the thread's join(), join( long), join(long, int), sleep(long), sleep(long, int) will also put it into a blocking state. If the thread calls its interrupt() method when it is in the blocked state, then its "interrupt state will be cleared and an InterruptedException exception will be received. For example, the thread enters the blocking state through wait(), and then interrupts the thread through interrupt(); call interrupt() will immediately set the thread's interrupt flag to "true", but because the thread is blocked, this"Interrupt flag" will be cleared immediately to "false", and at the same time, a # will be generated ##InterruptedException exception.

If a thread is blocked in a Selector selector, then when it is interrupted by interrupt(); The thread's interrupt flag will be set to true, and it will return immediately from the select operation.

If it does not fall into the above situation, then when the thread is interrupted through interrupt(), its interrupt mark will be set to "true".

Interrupting a "terminated thread" will result in no action.

8.1 Terminate the thread in the "blocked state"

Usually, we pass"Interrupt" way to terminate the thread in "blocked state".
When the thread enters the blocking state due to being called sleep(), wait(), join() and other methods; if the thread's ## is called at this time #interrupt()Set the thread's interrupt flag to true. Due to the blocking state, the interrupt mark will be cleared and an InterruptedException exception will be generated. Put InterruptedException until appropriate to terminate the thread

8.2 Terminate the thread in the "running state"

Usually, we pass"mark " way to terminate the thread in "Running state". Among them, include "Interruption mark" and "Additional addition mark.
(01) Terminate the thread by "Interrupt Flag".
The form is as follows:

@Overridepublic void run() {

while (!isInterrupted()) {

// Execute tasks... }

}

Explanation: isInterrupted() is to determine the interruption of the thread Is the tag true. When a thread is running and we need to terminate it; we can call the thread's interrupt() method, using the thread's interrupt flag as true , that is, isInterrupted() will return true. At this point, the while loop will exit.
Note: interrupt() will not terminate the "running state" the rout! It will set the thread's interrupt flag to true.

(02) Add additional tags by "".
The form is as follows:

private volatile boolean flag= true;protected void stopTask() {

flag = false;

}

@Overridepublic void run() {

while (flag) {

// Execute task ... }

}

Explanation: There is a flag tag in the thread, and its default value is true ; And we provide stopTask() to set the flag tag. When we need to terminate the thread, calling the thread's stopTask() method will allow the thread to exit the while loop.
Note: flag is defined as volatile type to ensure flag visibility. That is, after other threads modify flag through stopTask(), this thread can see the modified The value of flag.

Finally talk about interrupted() and isInterrupted().
interrupted() and isInterrupted() can both be used to detect the object’s interrupt flag .
The difference is that interrupted()In addition to returning the interrupt mark, it will also clear the interrupt mark(The upcoming interrupt mark Set to false); and isInterrupted() only returns the interrupt flag

9.Thread priority and daemon thread

Every thread has a priority. "High priority threads" will take precedence over "low priority threads "implement. Each thread can be marked as a daemon or non-daemon. When a new child thread is created within some running main thread, the child thread's priority is set equal to the priority of the main thread that created it. ", if and only if"The main thread that created it is a daemon thread" "The child thread will be the daemon thread". When the Java

virtual machine starts, there is usually a single non-daemon thread (the thread passes through

main()

method startup). JVM will continue to run until any of the following conditions occurs, JVM will terminate: (01) The exit()

method is called, and

exit() has permission to be executed normally. (02) All"

non-daemon threads

"are dead(That is, there are only "daemon threads in JVM ”). Each thread is marked as "

Daemon thread

"

or "User Thread". When only the daemon thread is running, JVM will automatically exit.

The above is the detailed content of Share some basic Java interview questions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template