Java Basics for Java Interview Preparation

1. The advantages of the Java language

object oriented, platform independent, memory management, security, multithreading, Java is interpreted

2. The difference between Java and C++

Multiple inheritance (multiple interfaces in java, not supported by classes, supported by C++),
automatic memory management,
preprocessing function
, goto statement (not supported by java)
references and pointers. It is impossible to directly manipulate the object itself in Java. All objects are pointed to by a reference, and the object itself must be accessed through this reference, including obtaining the value of member variables, changing the member variables of the object, calling the methods of the object, etc. In C++, there are three things: references, objects and pointers, all of which can access objects. In fact, references in Java are conceptually similar to pointers in C++. They are the address values ​​of stored objects in memory, but in Java, references lose some flexibility. For example, references in Java cannot be Addition and subtraction are performed like pointers in C++.

3. Pass-by-value and pass-by-reference

Variables are passed by value, meaning that a copy of the variable is passed. Therefore, even changing the variable copy will not affect the value of the source object. Objects are passed by reference, which means that what is passed is not the actual object, but a reference to the object. Therefore, external changes to the referenced object will be reflected in all objects. Java is essentially value-passing. For example, when a method is called, an object reference is passed in, and a copy will be constructed in the method stack to point to the same address with the same value as the reference variable. Changing the value of the reference will not change the value of the passed in reference.

4. The difference between static variables and instance variables

The difference in syntax definition: static keyword should be added before static variable, but not before instance variable. The difference when the program is running: Instance variables belong to the properties of an object, and an instance object must be created before the instance variables are allocated space before the instance variables can be used. Static variables do not belong to an instance object, but to a class, so they are also called class variables. As long as the program loads the bytecode of the class without creating any instance objects, the static variables will be allocated space, and the static variables can be used. In short, instance variables must be created before they can be used through this object, and static variables can be directly referenced using the class name.

5. JDK packages

JDK commonly used package java.lang: This is the basic class of the system, such as String, etc. are all here, this package is the only package that can be used without import java.io: Here are all input and output related classes , such as file operations, etc. java.net: There are classes related to the network, such as URL, URLConnection and so on. java.util: This is a system auxiliary class, especially the collection classes Collection, List, Map, etc. java.sql: This is the class for database operations, Connection, Statememt, ResultSet, etc.

6. Differences between JDK, JRE and JVM

JDK, JRE and JVM are core concepts of the Java programming language. Although they look similar and we as programmers don't care much about these concepts, they are different purpose-built products. This is a common Java interview question, and this article will explain each of these concepts and give the difference between them. 1) Java Development Kit (JDK) The Java Development Kit is the core component of the Java environment and provides all the tools, executables and binaries required to compile, debug and run a Java program. Including java basic jar package, virtual machine, javac and other executable files. JDK is a platform-specific software that has different installation packages for Windows, Mac and Unix systems. It can be said that JDK is a superset of JRE, which includes JRE's Java compiler, debugger and core classes. 2) Java Virtual Machine (JVM) JVM is the core of the Java programming language. When we run a program, the JVM is responsible for converting the bytecode into specific machine code. The JVM is also platform-specific and provides core Java methods such as memory management, garbage collection, and safety mechanisms. JVM is customizable, we can customize it through Java options (java options), such as configuring the upper and lower bounds of JVM memory. The JVM is called virtual because it provides an interface that is independent of the underlying operating system and machine hardware. This hardware and operating system independence is why Java programs can be written at once and executed in many places. 3) Java Runtime Environment (JRE) JRE is the implementation of JVM, which provides a platform for running Java programs. The JRE contains the JVM, Java binaries, and other class files for successful program execution. JRE does not contain any development tools like Java compiler, debugger, etc. If you just want to execute Java programs, you only need to install the JRE, there is no need to install the JDK.

The difference between JDK, JRE and JVM JDK is for development and JRE is for running Java programs. Both the JDK and JRE contain the JVM, which allows us to run Java programs. The JVM is the core of the Java programming language and is platform independent. Just-In-Time Compiler (JIT) Sometimes we hear the concept of JIT and say it's part of the JVM, which confuses us. JIT is the part of JVM that can optimize the process of converting bytecode into machine specific language by compiling similar bytecode at the same time This reduces the time required for the conversion process.

7. Is it possible to access non-static variables in a static environment

A static variable belongs to a class in Java, and its value is the same in all instances. When a class is loaded by the Java virtual machine, static variables are initialized. If your code tries to access non-static variables without an instance, the compiler will complain, because these variables have not been created and are not associated with any instance.

8. Final keyword usage in Java

(1) Modified class: Indicates that the class cannot be inherited; (2) Modified method: Indicates that the method cannot be overridden; (3) Modified variable: Indicates that a variable can only be assigned once and its value cannot be modified (constant).

assert
assertion is a common debugging method in software development, and many development languages ​​support this mechanism. Generally speaking, assertion is used to guarantee the most basic and critical correctness of the program. Assertion checks are usually turned on during development and testing. To improve performance, assertion checking is usually turned off after the software is released. In implementation, an assertion is a statement containing a Boolean expression that is assumed to be true when executed; an AssertionError is reported if the expression evaluates to false.

Assertions are used for debugging purposes:

assert(a > 0); // throws an AssertionError if a <= 0

Assertions can take two forms:

assert Expression1;
assert Expression1 : Expression2 ;

Expression1 should always yield a boolean value. Expression2 can be any expression that yields a value; this value is used to generate a string message that displays more debug information Assertions are disabled by default, to enable assertions at compile time, use the source 1.4 flag:

javac -source 1.4 Test.java

To enable assertions at runtime, use the -enableassertions or -ea flags. To choose to disable assertions at runtime, use the -da or -disableassertions flag.

9. What is the difference between final, finally, finalize?

final: The modifier (keyword) has three uses: if a class is declared final, it means that it can no longer derive new subclasses, that is, it cannot be inherited, so it is an antonym to abstract. Declaring variables as final ensures that they will not be changed during use. Variables declared as final must be given an initial value at the time of declaration, and can only be read and unmodified in subsequent references. Methods declared as final can also only be used and cannot be overridden in subclasses. finally: usually placed after try...catch, the code block is always executed, which means that whether the program is executed normally or an exception occurs, the code here can be executed as long as the JVM is not closed, and the code to release external resources can be written in finally in the block. finalize: A method defined in the Object class. In Java, the finalize() method is allowed to do the necessary cleanup work before the garbage collector clears the object from memory. This method is called by the garbage collector when the object is destroyed. By overriding the finalize() method, you can clean up system resources or perform other cleanup work.

10.& and &&

Both & and && can be used as operators of logical AND, representing logical AND (and). When the results of the expressions on both sides of the operator are both true, the entire operation result is true, otherwise, as long as one of them is false, then The result is false. && also has the function of short-circuiting, that is, if the first expression is false, the second expression is no longer evaluated. & can also be used as a bitwise operator, when the expressions on both sides of the & operator are not of type boolean, & Represents a bitwise AND operation.

11. Use the most efficient method to find out how many times 2 times 8 is

2 << 3, because shifting a number to the left by n bits is equivalent to multiplying it by the nth power of 2. Then, multiplying a number by 8 only needs to shift it to the left by 3 bits, and the bit operation CPU directly supports , the most efficient, so the most efficient way to multiply 2 by 8 is 2 << 3 .

The char type variable
char type can store a Chinese character, because the encoding used in Java is Unicode (do not choose any specific encoding, directly use the character number in the character set, this is the only way to unify), a char type occupies 2 bytes (16bit), so it is no problem to put a Chinese. Supplement: Using Unicode means that characters have different representations inside and outside the JVM. They are all Unicode inside the JVM. When this character is transferred from the inside of the JVM to the outside (for example, stored in the file system), encoding conversion is required. So Java has byte streams and character streams, as well as conversion streams that convert between character streams and byte streams, such as InputStreamReader and OutputStreamReader.

12. The difference between String and StringBuilder and StringBuffer

Answer: The Java platform provides two types of strings: String and StringBuffer / StringBuilder, which can store and manipulate strings. Among them, String is a read-only string, which means that the content of the string referenced by String cannot be changed. The string objects represented by the StringBuffer and StringBuilder classes can be modified directly. StringBuilder was introduced in JDK 1.5, and it has exactly the same method as StringBuffer, the difference is that it is used in a single-threaded environment, because all aspects of it are not modified by synchronized, so its efficiency is slightly higher than StringBuffer. There is an interview question asking: Are there any situations where string concatenation with + is more performant than calling the append method of StringBuffer / StringBuilder objects? If the string obtained after concatenation already exists in the static storage area, then using + for string concatenation is better than the append method of StringBuffer / StringBuilder.

13. String immutability

As for why the String class is designed as an immutable class, it is determined by its purpose. In fact, not only String, but many classes in the Java standard class library are immutable. When developing a system, we sometimes need to design immutable classes to pass a set of related values, which is also the embodiment of object-oriented thinking. Immutable classes have some advantages, such as because its objects are read-only, there will be no problems with concurrent access by multiple threads. Of course, there are also some disadvantages. For example, each different state must be represented by an object, which may cause performance problems. So the Java Standard Class Library also provides a variable version, StringBuffer. Javac compilation can optimize the expression of the direct addition of string constants. It is not necessary to wait until the runtime to perform the addition operation, but to remove the plus sign at compile time, and compile it directly into a result of the connection of these constants. So String s = "a" + "b" + "c" + "d"; produces only one object.

14. Immutable Objects

An object is immutable if its state cannot be changed after it has been created. Cannot change the state means that the member variables in the object cannot be changed, including the value of the basic data type, the variable of the reference type cannot point to other objects, and the state of the object pointed to by the reference type cannot be changed. How to create immutable classes

Declare a class as final so it cannot be inherited
Declare all members private so that direct access to those members is not allowed
Do not provide setters for
variables Declare all mutable members final so that only assignments can be made to them Initialize all members through the constructor at one time
and perform a deep copy (deep copy): If a class member is not a primitive or immutable class, it must be passed through a deep clone when the member is initialized (in) or get method (out). method to ensure the immutability of the class.
In the getter method, instead of returning the object itself directly, clone the object and return a copy of the object
http://www.cnblogs.com/yg_zhang/p/4355354.html http://www.importnew.com/7535. html

15. Why is String designed to be immutable**

Designing String to be immutable in Java is the result of comprehensive consideration of various factors, such as memory, synchronization, data structure, and security considerations.

The need for string constant pool. The implementation of string pool can save a lot of heap space at runtime, because different string variables all point to the same string in the pool. But if the string is mutable, then String interning will not be possible (Translator's Note: String interning means that only one is saved for different strings, that is, not multiple identical strings are saved.), because then , if a variable changes its value, the values ​​of other variables that point to this value also change.
thread safety considerations. The same string instance can be shared by multiple threads. This eliminates the need to use synchronization due to thread safety concerns. Strings themselves are thread-safe.
The class loader uses strings, and immutability provides security so that the correct class is loaded. For example, if you want to load the java.sql.Connection class, and this value is changed to myhacked.Connection, it will cause unknowable damage to your database.
Support hash mapping and caching. Because strings are immutable, the hashcode is cached when it is created and does not need to be recomputed. This makes strings very suitable as keys in Maps, which can be processed faster than other key objects. That's why the keys in HashMap tend to use strings.
http://blog.csdn.net/renfufei/article/details/16808775 http://www.codeceo.com/article/why-java-string-immutable.html http://www.importnew.com/7440. html http://www.importnew.com/16817.html

16. What is Java serialization and how to implement Java serialization

Serialization is a mechanism for processing object streams. The so-called object stream is to stream the content of objects. The streamed objects can be read and written, and the streamed objects can also be transmitted between networks. Serialization is to solve the problems caused by reading and writing to the object stream.

Serialization implementation: Implement the Serializable interface for the class that needs to be serialized. This interface has no methods to implement. Implements Serializable is just to mark the object as serializable, and then use an output stream (such as FileOutputStream) to construct An ObjectOutputStream (object stream) object, then, use the writeObject(Object obj) method of the ObjectOutputStream object to write out the object whose parameter is obj (that is, save its state), and use the input stream to restore it.

17. The difference between errors and exceptions (Error vs Exception)

  1. java.lang.Error: A subclass of Throwable, used to mark serious errors, representing system-level errors and exceptions that the program does not have to handle. A reasonable application should not go to try/catch this kind of error. It is a serious problem when recovery is not impossible but very difficult; such as memory overflow, it is impossible to expect the program to handle such a situation; java.lang.Exception: A subclass of Throwable, indicating that it needs to be caught or needs to be handled by the program , is a design or implementation issue; that is, it represents a situation that would never have occurred if the program was operating correctly. And user programs are encouraged to catch it.

  2. Error and RuntimeException and their subclasses are unchecked exceptions (unchecked exceptions), and all other Exception classes are checked exceptions (checked exceptions). caused by the problem. Usually thrown from a recoverable program, and it is best to be able to use program recovery from such an exception. Such as FileNotFoundException, ParseException and so on. The checked exception occurs in the compilation phase, and try...catch (or throws) must be used, otherwise the compilation will fail. unchecked exceptions: Usually exceptions that shouldn't have happened if everything was OK, but did happen. Occurs in the runtime, with uncertainty, mainly due to the logic problems of the program. For example ArrayIndexOutOfBoundException, ClassCastException etc. From the perspective of the language itself, the program should not catch such exceptions, although it is possible to catch and recover from exceptions such as RuntimeException, but end programmers are not encouraged to do so, because it is completely unnecessary. Because such errors are bugs themselves and should be fixed, the program should stop executing immediately when such errors occur. Therefore, in the face of Errors and unchecked exceptions, the program should be automatically terminated, and the programmer should not do things such as try/catch, but should find out the reason and modify the code logic. RuntimeException: The RuntimeException system includes wrong type conversion, array out-of-bounds access, and attempts to access null pointers, etc. The principle of dealing with RuntimeException is: If a RuntimeException occurs, it must be the programmer's fault. For example, array out-of-bounds access exceptions can be avoided by checking array subscripts and array bounds. Other checked exceptions (IOException, etc.) are generally external errors, such as trying to read data from the end of the file, etc. This is not an error of the program itself, but an external error that occurs in the application environment.

18. The return statement in try{}

Java's practice of allowing the return value to be changed in finally is not good, because if there is a finally code block, the return statement in try will not return to the caller immediately, but record the return value and wait until the finally code block is executed before calling it. or return its value, and then if the return value is modified in finally, it will cause a lot of trouble to the program

19. What are the similarities and differences between runtime exceptions and checked exceptions?

Answer: Exceptions indicate abnormal states that may occur during the running of the program. Runtime exceptions indicate exceptions that may be encountered in the normal operation of the virtual machine. They are common operating errors, which usually do not occur as long as the program is designed without problems. Checked exceptions are related to the context in which the program runs. Even if the program is designed correctly, it may still be caused by problems in use. The Java compiler requires that methods must declare to throw checked exceptions that may occur, but it does not require that methods must declare to throw uncaught runtime exceptions. Exceptions, like inheritance, are often abused in object-oriented programming. The God work "Effective Java" gives the following guidelines for the use of exceptions: Do not use exception handling for normal control flow (well-designed API It should not force its caller to use exceptions for normal control flow) Use checked exceptions for recoverable cases, use runtime exceptions for programming errors Avoid unnecessary use of checked exceptions (can be avoided by some means of state detection The occurrence of exceptions) Use standard exceptions first

20.throws、throw、try、catch、finally

Under normal circumstances, try is used to execute a program. If an exception occurs, the system will throw an exception. At this time, you can catch it by its type, or finally (finally) by the default handler. to handle; try is used to specify a block of procedures that prevents all "exceptions"; the catch clause immediately follows the try block and is used to specify the type of "exception" you want to catch; the throw statement is used to explicitly throw an "exception" Exception"; throws is used to indicate various "exceptions" that may be thrown by a member function; finally, a piece of code is executed to ensure that no matter what "exception" occurs in a piece of code;

Common runtime exception
1, NullPointerException null pointer reference exception 2, ClassCastException - type cast exception. 3. IllegalArgumentException - passing an illegal parameter exception. 4. IndexOutOfBoundsException - Subscript out of bounds exception 5. UnsupportedOperationException - Unsupported operation exception 6. ArithmeticException - Arithmetic operation exception 7. ArrayStoreException - Storing an object incompatible with the declared type into the array. 8. NegativeArraySizeException - Creating an array with a negative size Error Exception 9, NumberFormatException - Number Format Exception 10, SecurityException - Security Exception

What is the difference between throw and throws
The throw keyword is used to explicitly throw an exception in a program, on the contrary, the throws statement is used to indicate an exception that a method cannot handle. Each method must specify which exceptions cannot be handled, so the caller of the method can ensure that possible exceptions are handled. Multiple exceptions are separated by commas.

Can Switch use string as parameter?
Not before Java 1.7, String can be used as a parameter after Java 1.7. Integer type (byte, short int, int, long int), enumeration type, boolean, character type (char), string can be used, only floating point type cannot

21. The difference between equals and ==

1. == is an operator. 2. Equals is a method of the string object, which can be .(dot) out. Our comparison is nothing more than these two 1, basic data type comparison 2, reference object comparison 1, basic data type comparison == to compare whether two values ​​are equal. true for equality, false otherwise; equals cannot be used directly for comparison of primitive types. The base type needs to be converted to a wrapper for comparison. 2. Reference object comparison == and equals are to compare whether the addresses in the stack memory are equal. Equal to true otherwise false; need to pay attention to a few points: 1, string is a special reference type. For the comparison of two strings, both == and equals compare whether the strings are the same; 2. When you create two string objects, the addresses in the memory are not the same, you can assign the same value of . So the content of the string is the same. The reference address is not necessarily the same (the object address of the same content is not necessarily the same), but the reverse is true; 3. Basic data type comparison (except string) == and Equals are both comparison values;

22. What are the public methods of Object

protected Object clone() creates and returns a copy of this object. public boolean equals(Object obj) Indicates whether some other object is "equal" to this object. protected void finalize() This method is called by the object's garbage collector when the garbage collector determines that there are no more references to the object. public final native Class<?> getClass() Returns the runtime class of this Object. public int hashCode() returns the hash code value of this object. public String toString() returns the string representation of this object. public void notify() wakes up a single thread waiting on this object's monitor. public void notifyAll() wakes up all threads waiting on this object's monitor. public void wait() Causes the current thread to wait before other threads call the notify() method or notifyAll() method of this object. public void wait(long timeout) Causes the current thread to wait until other threads call the notify() method or notifyAll() method of this object, or until the specified amount of time has passed. public void wait(long timeout, int nanos) call the notify() method of this object in another thread or

Note: 1. If a class implements Cloneable, the clone method of Object will return a field-by-field copy of the object, otherwise a CloneNotSupportException will be thrown. java.lang.Cloneable is a denotative interface that does not contain any methods (see "effective java" p46 for details).

When overriding equals(), always override hashCode() (see "effective java" p39 for details) In each class that overrides the equals method, the hashCode method must also be overridden. Failure to do so will result in the general contract of Object.hashCode—equality The convention that the objects must have equal hash codes makes this class unable to work with all hash-based collections, such as HashMap, HashSet and HashTable. HashMap etc. use the hashCode() and equals() methods of the Key object to determine the index of the key-value pair. If objects with equals are considered to be the same object, then the put method puts the object in one hash bucket, and the get method may obtain the object from another hash bucket, because the objects passed in by these two methods are equals although equals The same, but the hashCode may be different, and the hashMap locates the hash bucket position according to the hashCode, resulting in different hash buckets. The role of Hashcode.
The existence of hashCode is mainly used for the quickness of search, such as Hashtable, HashMap, etc. hashCode is used to determine the storage address of the object in the hash storage structure;
compare whether the objects are the same. The following is the convention about hashCode: 1. If the two objects are the same, it is applicable to the equals(java.lang.Object) method, then the hashCode of the two objects must be the same; 2. If the equals method of the object is overridden, Then the hashCode of the object is also rewritten as much as possible, and the object used to generate the hashCode must be the same as the one used in the equals method, otherwise it will violate the second point mentioned above; 3. The hashCode of the two objects is the same, not necessarily It means that two objects are the same, that is, it is not necessarily applicable to the equals(java.lang.Object) method. It can only indicate that these two objects are stored in a hash storage structure, such as Hashtable, and they are "stored in the same basket".

23. The difference between String, StringBuffer and StringBuilder

String is a string constant and is an immutable class. If you want to manipulate a small amount of data
, StringBuffer is a string variable, which is thread-safe. Multi-threaded operation of the string buffer under the operation of large amounts of data
StringBuilder is a string variable, not thread-safe. The speed of operating a large amount of data under single-threaded string buffer operation: String splicing of StringBuilder > StringBuffer > String String objects is actually interpreted by JVM as the splicing of StringBuffer objects, so the speed of String objects will not be slower than StringBuffer objects at these times. , and especially in the following string object generation, String efficiency is much faster than StringBuffer: String S1 = "This is only a" + "simple" + "test"; StringBuffer Sb = new StringBuilder("This is only a").append("simple").append("test"); see: http://www.findspace.name/easycoding/1090

24. try catch finally, if there is return in try, is finally still executed?

1) Regardless of whether there is an exception, the code in the finally block will be executed. 2) When there is a return in try and catch, finally will still be executed. The value after the operation, but first save the value to be returned, no matter how the code in finally, the returned value will not change, it is still the value saved before), so the return value of the function is before the finally execution 4) It is best not to include return in finally, otherwise the program will exit early, and the return value is not the return value saved in try or catch

25. What is UnsupportedOperationException

UnsupportedOperationException is an exception used to indicate that the operation is not supported. Used extensively in JDK classes, the collection framework java.util.Collections.UnmodifiableCollection will throw this exception in all add and remove operations.

26. Excption and Error package structure

Java value transfer problem
1. Object is passed by reference 2. Primitive type is passed by value 3. String, Integer, Double and other immutable types do not provide self-modifying functions, and each operation generates a new object, so it needs special treatment. It can be considered as pass-by-value. Integer is the same as String. The class variable that holds the value is a Final property, which cannot be modified, but can only be reassigned/generated into a new object. When an Integer is passed into the method as a method parameter, the assignment to it will cause the reference of the original Integer to be pointed to the stack address in the method, and the pointer to the address of the original class variable will be lost. Doing any operation on the assigned Integer object will not affect the original object.

27. Modifier order

public protected private abstract static final transient volatile synchronized native strictfp

Guess you like

Origin blog.csdn.net/weixin_43934939/article/details/114079584