Advantages of the 1.Java language
Object-oriented, platform independent, memory management, security, multi-threading, Java is interpreted
The difference between 2.Java and C + +
- Multiple Inheritance (Java interface multiplicity, class not supported, C + + support)
- Automatic memory management
- Preprocessing capabilities
- Goto Statement (Java not supported)
- references with pointers . In Java, it is not possible to manipulate the object itself directly, all objects are pointed to by a reference, which must be used to access the object itself, including getting the value of the member variable, changing the object's member variables, invoking the object's methods, and so on. In C + + There are references, objects and pointers to three things, and these three things can access the object. In fact, the references in Java are conceptually similar to the pointers in C + +, they are the address values of the stored object in memory, but in Java, the reference loses some flexibility, such as a reference in Java cannot be added and reduced as a pointer in C + +.
3. Value passing and reference passing
A variable is passed by value, which means that a copy of the variable is passed. Therefore, even if you change the copy of the variable, the value of the source object is not affected. object is passed by reference, meaning that it is not the actual object, but the reference to the object . Therefore, changes made externally to the referenced object are reflected on all objects. Java is essentially a value pass, such as when a method call passes in an object reference, a copy is constructed in the method stack and the reference variable value is the same as the same address. If you change the value of the reference, it does not change the value of the incoming reference.
4. The difference between a static variable and an instance variable
The difference between the syntax definitions : Static variables are added with the static keyword, and the instance variable is not added before. The difference when the program runs : instance variables belong to an object's properties, and an instance object must be created where the instance variable is allocated space before the instance variable can be used. Static variables are not part of an instance object, but belong to a class, so also known as class variables, as long as the program loads the class's bytecode, without creating any instance objects, static variables will be allocated space, static variables can be used. In summary, an instance variable must be created before it can be used by the object, and a static variable can be referenced directly using the class name.
5.JDK package.
JDK Common Package Java.lang: This is the basic class of the system, such as String, etc. are in this, the package is the only one can be used without import of the package JAVA.IO: This is all the input and output related classes, such as file operations, such as java.net: This is a network-related classes, such as Url,urlconnection. Java.util: This is the system auxiliary class, especially the collection class Collection,list,map and so on. java.sql: This is the database operation class, Connection, Statememt,resultset, etc.
6.JDK, the difference between JRE and JVM
jdk,jre and JVM are the core concepts of the Java programming language. Although they look similar, we don't care about these concepts as programmers, but they are different products for specific purposes. This is a common Java interview problem, and this article explains the concepts and gives the difference between them. 1) Java Development Kit (JDK) The Java SDK 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. Includes Java base jar package, virtual machine, Javac and other executable files. The JDK is a platform-specific software that has different installation packages for Windows,mac and Unix systems. It can be said that the JDK is a superset of the JRE, which contains the Java compiler for the JRE, the debugger, and the core class. 2) Java virtual machine (JVM) The JVM is at the heart of the Java programming language. When we run a program, the JVM is responsible for converting bytecode to specific machine code. The JVM is also platform-specific and provides core Java methods, such as memory management, garbage collection, and security mechanisms. The JVM is customizable, and we can customize it with Java options, such as configuring the upper and lower bounds of JVM memory. The JVM is called virtual because it provides an interface that does not depend on the underlying operating system and machine hardware. This hardware-and OS-independent feature is why Java programs can write multiple executions at once. 3) Java Runtime Environment (JRE) The JRE is the implementation of the JVM, which provides a platform for running Java programs. The JRE contains the JVM, Java binaries, and other class files that successfully execute the program . The JRE does not contain any development tools such as the Java compiler, the debugger, and so on. If you just want to execute a Java program, you only need to install the JRE, without the need to install the JDK.
the difference between JDK, JRE, and JVM The JDK is for development and the JRE is used to run Java programs. Both the JDK and the JRE contain the JVM, which allows us to run Java programs. The JVM is the core of the Java programming language and has platform independence. instant compiler (JIT) Sometimes we hear the concept of JIT and say it's part of the JVM, which makes us very confused. JIT is part of the JVM that can compile similar bytecode at the same time to optimize the process of converting bytecode into machine-specific languages, thus converting optimized bytecode into machine-specific languages, thus reducing the time it takes to convert the process.
7. Whether non-static variables can be accessed in the static environment
The static variable belongs to the class in Java, and it has the same value in all instances. Static variables are initialized when the class is airborne into Java virtual. If your code tries to access a non-static variable without an instance, the compiler will give an error because the variables have not been created yet and are not associated with any instances.
Final keyword usage in Java
(1) Modifier class: Indicates that the class cannot be inherited, (2) The Modification method: Indicates that the method cannot be overwritten; (3) modifier variable: Indicates that the value cannot be modified (constant) after the variable can be assigned only once.
Assert
Assertion (assertion) is a common debugging method in software development, which is supported in many development languages. In general, assertion is used to ensure the most basic and critical correctness of the program . Assertion inspection is usually turned on during development and testing. To improve performance, the assertion check is usually turned off after the software is released. In the implementation, the assertion is a statement that contains a Boolean expression that is assumed to be true when the statement is executed, and a 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 be of two forms:
assert Expression1; assert Expression1 : Expression2 ;
Expression1 should always produce a Boolean value. Expression2 can be any expression that yields a value, and this value is used to generate a string that displays more debugging information the assertion is disabled by default, and to enable assertions at compile time, use the source 1.4 tag:
javac -source 1.4 Test.java
To enable assertions at run time, you can use-enableassertions or-ea tags. To choose to disable assertions at run time, you can use-da or-disableassertions tags.
Final, finally, finalize the difference?
final: modifier (keyword) has three usages: if a class is declared final, it means that it can no longer derive a new subclass, i.e. it cannot be inherited, so it and abstract are antonyms. Declaring variables as final ensures that they are not changed in use, and that the variable declared as final must be given the initial value at the time of declaration, whereas in subsequent references only the non-modifiable can be read. A method that is declared final can also be used only and cannot be overridden in a subclass. finally: usually put in the back of the Try...catch code block, which means that the program regardless of normal execution or exception, the code as long as the JVM does not shut down can be executed, you can release the external resources to write code in the finally block. Finalize: Methods defined in the object class that allow the use of the Finalize () method in Java to do the necessary cleanup before the garbage collector clears the object from memory. This method is called by the garbage collector when the object is destroyed, and by overriding the Finalize () method, you can defragment the system resources or perform other cleanup work.
& and &&
Both & and && can be used as the logical AND operator, representing logic and (and), when the result of an expression on either side of the operator is true, the entire result is true, otherwise the result is false if one of the parties is false. && also has a short-circuit function , 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 expression on either side of the & operator is not a Boolean type,& Represents a bitwise AND operation.
Use the most efficient method to calculate 2 times 8
2 << 3, because moving a number to the left n bit, is the equivalent of multiplying by 2 of the N-square, then, a number multiplied by 8 to move it to the left 3 bits, and the bit operation CPU directly support, the most efficient, so, 2 times 8, the most efficient method is 2 << 3 。
Char type variable
The char type can store a Chinese character because the encoding used in Java is Unicode (not selecting any particular encoding, directly using the character's number in the character set, which is the only way to unify), and a char type is 2 bytes (16bit), so putting a Chinese is no problem. Supplement: Using Unicode means that characters have different representations both inside and outside the JVM, Unicode within the JVM, and encoded when the character is transferred from inside the JVM to the outside (for example, to a file system). So there is a stream of bytes and characters in Java, as well as translation streams that convert between character streams and byte streams, such as InputStreamReader and Outputstreamreader.
The difference between String and StringBuilder, StringBuffer
A: The Java platform provides two types of strings: string and Stringbuffer/stringbuilder, which can store and manipulate strings. Where string is a read-only string, meaning string content referenced by string cannot be changed. The string objects represented by the StringBuffer and StringBuilder classes can be modified directly. StringBuilder is introduced in JDK 1.5, and it is exactly the same as the StringBuffer method, except that it is used in a single-threaded environment because all aspects of it are not synchronized decorated, so it is more efficient than StringBuffer slightly higher. There is a face question question: Is there any case that using + to make a string connection is better than calling the Append method of the Stringbuffer/stringbuilder object? If the resulting string is already present in the static store, then a string connection with + is better than the Stringbuffer/stringbuilder append method.
String immutability
As for why the String class is designed as an immutable class, it is the purpose of its decision. In fact, not only String, but many classes in the Java Standard class library are immutable. In the development of a system, we sometimes need to design immutable classes to pass a set of related values, which is the embodiment of object-oriented thinking. Immutable classes have some advantages, such as because their objects are read-only, so there is no problem with multithreading concurrent access. Of course, there are some shortcomings, such as each different state to have an object to represent, may cause performance problems. So the Java Standard class library also provides a mutable version, the StringBuffer. The Javac compilation can be optimized for expressions that add directly to string constants without having to wait for the runtime to do addition processing, but rather to compile with the plus sign removed , compiling it directly into a result of these constants. So String s= "a" + "B" + "C" + "D"; only one object is generated.
Immutable objects
If an object cannot change its state after it has been created, then the object is immutable. The inability to change the state means that the member variables within the object cannot be changed, that the value of the underlying data type cannot be changed, that a variable of the reference type cannot point to other objects, and that the state of the object to which the reference type points cannot be changed. How to create immutable classes
- Declares a class as final, so it cannot be inherited
- Declare all members private so that you do not allow direct access to those Members
- Do not provide setter methods for variables
- Declare all mutable members as final so that they can be assigned only once
- Initialize all members through the constructor, deep copy: If a class member is not a primitive variable (primitive) or an immutable class, you must ensure that the class is immutable by using the deep clone method in the member initialization (in) or Get method (out).
- In the getter method, do not directly return the object itself, but instead 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
Why is a string designed to be immutable * *
In Java, the design of string as immutable is taking into account the results of various factors, such as memory, synchronization, data structure and security considerations.
- The need for a string constant pool. The implementation of a string pool can save a lot of heap space at run time, because different string variables point to the same string in the pool. But if the string is mutable, then string interning will not be implemented (translator Note: string interning refers to just one save for different strings, that is, not many of the same strings are saved.) Because then, if the variable changes its value, the value of the other variable that points to that value will also change.
- Thread safety considerations. The same string instance can be shared by multiple threads. This will not use synchronization because of thread-safety issues. The string itself is thread-safe.
- The ClassLoader uses a string, 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 an unknown damage to your database.
- Hash mapping and caching are supported. Because the string is immutable, hashcode is cached when it is created and does not need to be recalculated. This makes the string well suited as a key in the map, and the string is processed faster than other key objects. This is where 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
What is Java serialization and how to implement Java serialization
Serialization is a mechanism for dealing with the flow of objects, so-called object flow is the flow of the object's contents . It is possible to read and write to a Fluidized object, or to transfer the streamed object between the networks . Serialization is a problem that is raised when reading and writing to an object stream.
Serialization implementation: Implement the Serializable interface for the class that needs to be serialized, there is no method to implement it, implements Serializable just to annotate that the object is serializable, and then use an output stream ( such as: FileOutputStream) to construct a ObjectOutputStream object, followed by the WriteObject (object obj) of the ObjectOutputStream object method to write out (that is, save its state) the object with the parameter obj, and the input stream to restore.
Differences between errors and exceptions (Error vs Exception)
1) java.lang.Error:Throwable subclasses, which are used to mark critical errors, represent system-level errors and exceptions that the program does not have to handle . A reasonable application should not go try/catch this error. is a serious problem in situations where recovery is not impossible but difficult, such as memory overflow , it is impossible to expect the program to handle such a situation; java.lang.Exception:Throwable subclasses, Represents an exception that needs to be captured or handled by a program, which is a design or implementation problem , that is, if the program is running normally, it never happens. and encourage the user program to catch it.
2) Error and RuntimeException and their subclasses areunchecked exception (unchecked exceptions), and all other Exception classes are checked for exceptions (checked exceptions)checked Exceptions:context, even if the programming is correct, can still be caused by the use of problems. is usually thrown out of a program that can be recovered, and it is best to use the program recovery from this exception。 Like whatFileNotFoundException, ParseException and so on. The checked exception occurs during the compile phase and must be used Try...catch (or throws) or the compilation will not pass.Unchecked Exceptions: It's usually the exception that happens if all the normal scripts don't happen.occur in the run-time, with uncertainty, mainly due to the logic of the program problems caused by。 such as Arrayindexoutofboundexception, classcastexception and so on. From the point of view of the language itself, the program should not catch such exceptions, although it can catch and recover from exceptions such as runtimeexception, but does not encourage the terminal programmer to do so, because it is not necessary at all. Because such errors are bugs in themselves, they should be fixed and the program should stop executing immediately when such errors occur. Therefore, in the face of Errors and unchecked exceptions should let the program automatically terminate execution, programmers should not do things such as try/catch, but should find out why, modify the code logic. The runtimeexception:runtimeexception system includes wrong type conversions, array cross-border access, and attempts to access null pointers and so on. The principle of dealing with runtimeexception is that if a runtimeexception occurs, it must be a programmer's fault. For example, you can avoid array out-of-bounds access exceptions by examining array subscripts and arrays boundaries. Other (IOException, etc.) checked exceptions are generally external errors, such as trying to read data from the end of a file, which is not an error in the program itself, but an external error that occurs in the application environment.
Return statement in try{}
It is not good for Java to allow the return value to be changed in Finally, because if a finally block exists, the return statement in the try does not return the caller immediately, but instead records the return value until the finally code block finishes executing before returning its value to the caller, and then if the fi The return value is modified in the nally, which can cause great problems for the program.
What is the difference between a run-time exception and a inspected exception?
A: An exception indicates an unhealthy state that may occur during a program's operation, a run-time exception that represents an exception that may be encountered during a typical operation of a virtual machine, and is a common running error that usually does not occur if no problem is programmed. The exception that is checked is related to the context in which the program is running , even if it is programmed correctly, and can still be caused by a problem . The Java compiler requires that the method must declare the exception that is expected to be thrown, but does not require that an uncaught run-time exception be declared. Exceptions and inheritance are often misused in object-oriented programming, and God's use of exceptions in effective Java gives the following guidelines: Do not use exception handling for normal flow of control (well-designed APIs should not force its callers to use exceptions for normal flow of control) , using a run-time exception for programming errors in cases where recovery is possible Avoid unnecessary use of checked exceptions (which can be avoided by means of stateful detection) precedence of standard exceptions each method throws an exception that has the atomicity of the document to keep the exception in the catch The caught exception is ignored in the
Throws, throw, try, catch, finally
In general, a try to execute a program, if an exception occurs, the system throws (throw) an exception, when you can catch it by its type (catch) it, or finally (finally) by the default processor, try to specify a block to prevent all "exceptions" program The catch clause immediately follows the TRY block to specify the type of "exception" you want to catch, and the throw statement is used to explicitly throw an "exception"; throws is used to indicate the various "exceptions" that a member function might throw; finally to make sure that a piece of code doesn't matter what "exception" is occurring have been executed for a period of code;
Common runtime exception
1. NullPointerException null pointer refers to exception 2, classcastexception-type cast exception. 3, illegalargumentexception-Pass illegal parameter exception. 4, Indexoutofboundsexception-subscript out-of-bounds exception 5, unsupportedoperationexception-Unsupported Operation exception 6, ArithmeticException-Arithmetic operation exception 7, Arraystoreexception-Storing an incompatible object with a declaration type in an array exception 8, negativearraysizeexception-Creating an array with a negative size error exception 9, NumberFormatException- Number format Exception 10, SecurityException-Security exception
What's the difference between throw and throws?
The Throw keyword is used to explicitly throw an exception in a program, whereas a throws statement is used to indicate an exception that the method cannot handle. Each method must specify which exceptions cannot be handled, so the caller of the method will be able to ensure that the exceptions that may occur are handled, and that multiple exceptions are separated by commas.
Can switch use string to make arguments?
Java 1.7 is not possible before, Java 1.7 after string can be used as a parameter. Integer (byte,short int,int,long int), enum type, Boolean, character type (char), string can be, except floating-point type can not
The difference between equals and = =
1, = = is an operator. 2, Equals is the method of the string object, you can. (dot) out. We compare these two kinds of 1, the basic data type comparison 2, the Reference object comparison 1, the basic data type comparison = = Compare two values are equal. Equal to True otherwise false; equals cannot be used directly for comparison of base types. You need to convert the base type to a wrapper for comparison. 2, Reference object comparison = = and equals are compared to the address in the stack memory is equal. Equal to true otherwise false; note the following: 1. String is a special reference type. For a comparison of two strings, both = = and equals are strings identical, 2, when you create two string objects, the address in memory is not the same, you can assign the same value. So the contents of the string are 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 positive; 3. Basic data type comparisons (except string) = = and Equals are both comparison values;
What are the common methods of object?
Protected Object Clone () creates and returns a copy of this object. public boolean equals (Object obj) indicates whether an 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 run-time class for this Object. public int hashcode () returns the hash code value of the object. The public string toString () returns the string representation of the object. public void Notify () wakes a single thread waiting on this object monitor. public void Notifyall () wakes up all the threads waiting on this object monitor. public void Wait () causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method. public void Wait (long timeout) causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method, or exceeds the specified amount of time. public void Wait (long timeout, int Nanos) calls this object's Notify () method on another thread or
Note: 1. If a class implements the Cloneable,object clone method, it returns a domain-wise copy of the object, otherwise it throws a Clonenotsupportexception exception. Java.lang.Cloneable is an indicative interface and does not contain any methods (see effective Java p46).
- overriding Equals () always overwrites hashcode () (see effective Java P39) and must override the Hashcode method in each class that overrides the Equals method. Failure to do so will result in the general conventions of the object.hashcode--- equal objects must have equal hash code conventions , resulting in the class not being able to assemble all the hash-based collections that work together, such that the collection has HashMap, HashSet and Hashtable. HashMap uses the hashcode () and Equals () methods of the Key object to determine the index of the key-value pair. If an object equal to equals is considered to be the same object, then the Put method places the object in a hash bucket, and the Get method may fetch the object from another hash bucket because the two methods pass in the same object, but the hashcode may be different, The hashmap location of the hash bucket according to the hashcode causes it to appear in different hash buckets. The role of Hashcode.
- The existence of hashcode is mainly used to find the shortcut, such as Hashtable,hashmap, Hashcode is used in the hash storage structure to determine the object's storage address;
- Compare whether the objects are the same. This is about the Hashcode Convention: 1, if two objects are the same, is applicable to the Equals (Java.lang.Object) method, then the two objects hashcode must be the same; 2, if the object's Equals method is overridden, Then the object's hashcode also try to rewrite, and produce hashcode use the object, must be consistent with the use of the Equals method, otherwise it will violate the above mentioned 2nd, 3, two objects hashcode the same, does not necessarily mean that two objects are the same, That is not necessarily applicable to the Equals (Java.lang.Object) method, it is only possible to show that the two objects are in the hash storage structure, such as Hashtable, they are "stored in the same basket".
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 with
- StringBuffer is a string variable and is thread-safe. Multi-threaded operation with a string buffer to manipulate large amounts of data
- StringBuilder is a string variable, non-thread safe. Single-threaded operation string buffers operation of a large amount of data speed: StringBuilder > StringBuffer > String concatenation of a string string object is actually a concatenation of the StringBuffer objects that are interpreted by the JVM, so these times The speed of a string object is not slower than the StringBuffer object, especially in the following string object generation, where string efficiency is far faster than StringBuffer: string S1 = "This is only a" + "simple" + "Test"; StringBuffer Sb = new StringBuilder ("This was only a"). Append ("simple"). Append ("test"); See also: http://www.findspace.name/easycoding/1090
Do you have return,finally in Try Catch finally,try?
1) No matter if there is an exception to the wood, the code in the Finally block executes 2) when there is a return in the try and catch, finally will still execute 3) finally is executed after the expression operation after return (at this time does not return the value after the operation, Instead, the value to be returned is saved, regardless of the code in the Finally, the returned value will not change, still is the previously saved value, so the function return value is determined before finally execution 4) Finally, it is best not to include return, Otherwise the program exits prematurely and the return value is not the return value saved in a try or catch
What is Unsupportedoperationexception?
Unsupportedoperationexception is an exception that is used to indicate that an operation is not supported. has been used extensively in JDK classes, the java.util.Collections.UnmodifiableCollection will throw this exception in all add and remove operations in the collection framework.
Excption and error packet structure Java value transfer problem
1. The object is a reference 2. The original type is the value 3.string,integer, double immutable type because there is no function to provide its own modification, each operation is a new object, so special treatment. Can be considered as a pass value. Integer is the same as String. The class variable that holds the value is the final attribute, cannot be modified, and can only be re-assigned/generated new object. When an integer is passed into the method as a method parameter, its assignment causes the reference of the original integer to be pointed to the stack address within the method and loses its point to the original class variable address. Any action done on the assigned integer object does not affect the original object.
Integer
Http://www.cnblogs.com/dolphin0520/p/3780005.html
Modifier order
Public protected private abstract static final transient volatile synchronized native STRICTFP
Java basics of preparing for the interview