Details! Focus! Easy wrong point! --Interview Java Basics (II.)

Source: Internet
Author: User
Tags finally block

Today to share the Java focus on the second part of the wrong point, but also the interview needs of all students to prepare, welcome to communicate correct.

1. String creation and storage mechanism: When a string is created, it is first found in the constant pool whether the same string is already defined, based on the return value of equals of type string and, if defined, directly to the reference.
You do not need to create a new object at this time, if it is not defined, create the object first, then add it to the string pool and return its reference. (Example: New String ("AAA") may have created 1 or 2 objects if the constant pool originally had AAA
Then an object is created, and if there is no AAA, two objects are created)

The difference between 2.==,equals,hashcode:
1) If you want to compare two basic types of data or if two reference variables are equal, use the = = operator only.
2) equals is one of the methods provided by the object class, and the equals defined in the object class is an object that is compared directly with the = = operator (the value of the comparison string is equal to equals, and the reference is equal to = =).
3) The Hashcode method is inherited from the object method and is used to identify whether two objects are equal. The Hashcode method in the object class returns an object that is converted to an int value in the memory address, so if the Hashcode method is not overridden, the hashcode of any object
are not equal.

3.string,stringbuffer,stringbuilder,stringtokenizer:
1) Once a string object is created, its value cannot be modified (the reference is immutable). StringBuffer, however, can change the class.
2) A string can be instantiated with a constructor or an assignment symbol, whereas StringBuffer can only be initialized with constructors.
3) StringBuilder and StringBuffer are also used to modify strings, but StringBuilder is not thread-safe, so StringBuilder is more efficient and uses stringbuffer when multiple threads are accessed.
4) StringTokenizer is a tool for splitting strings.
Note: String s= "" and s=null are not the same. S=null represents S does not point to any one string, while s= "" means S is a reference to an empty string.

4. About Arrays:
1) in C and C + +, the array name knowledge is a pointer to the first element of the array. In Java, arrays have not only their own properties, but also some methods that can be called, from this point of view, the array in Java is an object.
2) When the Java array is defined, the array elements are not allocated storage space, so the length of the array is not required in [].
3) When the Java array is created, it is initialized to the corresponding initial value based on the type of data the array holds.
4) When declaring a two-dimensional array in Java, [] must be empty, and the second dimension of the two-dimensional array can be of different lengths (for example, define a two-dimensional array, the first row two columns, and the second row three columns).

5.length length () and size (): The array in Java provides the length property to get the lengths of the array, and the length () method is for the string to evaluate the lengths of the strings. The size method is for the reflection collection, which gets how many elements there are.

Execution of the 6.finally statement: The function of the finally block is to ensure that the code inside the finally block will be executed no matter what happens. If there is a return in try-finally or catch-finally, then the Retrun statement in the finally block overwrites the return statement elsewhere.
But the finally statement in Java is not bound to be executed, and if an exception is encountered or exit terminates.

7. Runtime exceptions and common exceptions: two kinds of error exception classes are available in Java: Error and exception, they have a common parent class-throwable.
1) error indicates that the program has a very serious error during operation and is unrecoverable, a critical error at the JVM level, many of which are caused by a logical error, which is the error that should be resolved and is usually not recommended for capture.
2) exception represents a recoverable exception that contains two types: Check for exceptions and run-time exceptions.

8. Exception handling There are several issues to note:
1) Java exception handling uses the concept of polymorphism, when catching an exception, you should first capture the subclass, capturing the base class's exception information.
2) throw an exception as early as possible, treat the caught exception as an exception, or recover from the error, or let the program continue execution.
3) You can customize the exception class according to the actual requirements, as long as these custom exception classes inherit from the exception class.
4) exception can be processed on processing, can not be processed on the throw. For a generic exception, if it cannot be processed, it is converted to a run-time exception throw.

9.Java IO stream: Can be divided into two main categories: character stream and byte stream.
Character stream: In characters of 16bit, according to the Code table mapping character, can read out multiple bytes at a time. Contains reader and writer two abstract classes.
Byte stream: In bytes of 8bit, contains two abstract class Inputstream,outputstream.
The main difference: the byte stream does not use the cache when it processes the input and output, and the character stream uses the cache.

There are two types of sockets in 10.Java Socket:java: The connection-oriented socket communication protocol (TCP, the Transmission Control Protocol) and the non-connection-oriented socket communication protocol (UDP, User Datagram Protocol). Any socket is uniquely determined by the IP address and port number.

11.NIO: Non-blocking mode compared to a traditional socket, using NIO is much more efficient than a socket when dealing with a large number of concurrent requests.

12.Java Serialization: Java provides two ways to persist objects, serialization and external serialization (serialization is a process that describes an object as a sequence of bytes, and is used to solve problems that arise when reading and writing to an object stream).
All classes in Java that implement serialization must implement the Serializable interface.
Features of serialization:
1) If a class can be serialized, its subclasses can also be serialized.
2) because static represents a member of a class, transient represents temporary data, which is declared to be non-serializable for both types of data members.
Situations that need to be serialized:
1) The object needs to be sent over the network, or the state of the object needs to be persisted into the database or file.
2) serialization enables deep replication, which means that referenced objects can be copied.

13.Java Interpretation Execution Order: code loading, code validation, code execution.
Java bytecode execution is also divided into two ways: The real-time compilation method, the interpretation of execution, the immediate compilation means that the interpreter first compiles the bytecode into machine code, and then executes the machine code;
The way to explain execution is worth it. The interpreter accomplishes all the operations of the Java bytecode program by explaining and executing a small piece of code each time.

The loading principle of class file in 14.Java:
The way classes are loaded is divided into implicit loading and explicit loading. Implicit loading is when a program creates an object using new and so on, it implicitly calls the class-loader and loads the corresponding class into the JVM.
Explicit loading refers to the class that is required to load into the JVM by calling the Class.forName method directly.

15. Main steps of class loading:
1) load. Find the corresponding class file based on the lookup path and pour it in.
2) links. Check the correctness of the class file. Allocates storage space for static variables in a class. Replace the symbol reference with a direct reference.
3) Initialize. Perform initialization work on static variables and static blocks of code.

16.Java garbage collection mechanism: the Java language itself does not give developers the means to explicitly release allocated memory, that is, developers cannot invoke the garbage collector in real time, but develop
A person can notify the garbage collector to run by calling the System.GC () method. The JVM does not guarantee that the garbage collector will run immediately.

17.Java of memory leaks: 1) The space requested in the heap is not released, 2) the object is no longer in use, but is still stored in memory.
A reference to the garbage collection mechanism resolves the first case.
There are four things that can cause a memory leak: 1) Static collection Class 2) database connection, network connection, IO connection, etc. 3) Listener 4) variable irrational scope 5) Singleton mode

Stacks in 18.Java: stacks are used primarily to store basic data types and reference variables, and heaps are used to store objects created at run time, typically objects created with the new keyword are stored in heap memory.

19.Java Collections Framework: Contains a large number of collection interfaces and their implementation classes. such as: List,queue,set,stack and map and so on.
Among them Set,list,map:
Set features: The set of Chinese elements can not be repeated, there are two implementation classes HashSet and TreeSet, wherein TreeSet implements the SortedSet interface, is ordered.
List features: You can save duplicate objects, Linkedlist,arraylist,vector all implement the list interface.
Map Features: Provides a data interface that maps from a key to a value. It is used to hold key-value pairs. The value is repeatable and the key is unique. Both Hashmap,treemap,linkedhashmap,weakhashmap and Identityhashmap in Java implement this interface.

20.Iterator iterators: Three important methods
1) The container's iterator () returns a iterator and then returns the first element through the next method of iterator.
2) Hasnext Determine if there are elements.
3) The Remove method removes the iterator element from China.
Precautions:
1) iterators can only traverse the collection in a forward direction, suitable for removing elements, Listiterator inherits from iterator specifically for List can traverse list in two directions, while supporting element modification.
2) The iterator thread security issue, when using iterators to traverse the container, note that the operation of the container is placed in the synchronized code block.

21.linkedlist,arraylist,vector differences:
LinkedList equivalent to the data structure of the linked list, suitable for adding and deleting operations, arraylist,vector equivalent to the array data structure, suitable for reading operations.
The biggest difference between arraylist,vector is that vectors are thread-safe and ArrayList are not thread-safe, because vectors are thread-safe, and their performance is slightly less than ArrayList.

What is the difference between 22.hashmap,treemap,hashtable,weakhashmap:
1) HashMap is a lightweight implementation of Hashtable (non-thread-safe), they all completed the map interface, the main difference is that HASHMAP allows null key values, but only one is allowed to be empty, Hashtable not allowed.
2) HashMap hashtable contains method removed, changed to Containsvalue and ContainsKey. HashTable inherits from dictionary and HashMap is the implementation of the map interface.
3) HashTable is thread-safe hashmap not.
4) inserting and deleting and locating elements in map HashMap is the best choice. TreeMap is better if you need to sort or customize the order traversal key. If the order you want to enter is the same as the order of the output, Linkedhashmap is more appropriate.

23. When using a custom class as a key value for HashMap, be aware that:
1) override the Equals and Hashcode methods if you want to customize equality based on the object's related properties.
2) When customizing multiple items of a class as HashMap key, it is best to design this class as an immutable class.
3) If two objects are equal, then they have the same hashcode, which is not true.

24. What are the threads, what are the advantages, and what is the difference between the processes:
Threads have four states: run, ready, hang, end.
A process is a program that is executing, and a thread can be considered a lightweight process, the smallest unit that a program executes, a process that can have multiple threads, a program's memory space shared between threads (code snippets, data segments, heap space)
And some process-level resources, but each thread has its own stack space.
Advantages of Multithreading:
1) Reduce the response time of the program.
2) thread creation and switching overhead are less expensive than processes.
3) Multi-CPU or multi-core computer itself has multithreading capability, if single thread is used, computer resources are wasted.
4) Multithreading can simplify the structure of the program, easy to understand.

25. How to achieve synchronization: Use the Synchronized keyword to achieve synchronization: two ways:
1) Synchronous code blocks are used for synchronization.
2) Implement using synchronous method (the method is declared with synchronized keyword).

26.Java implements multi-threading three ways:
1) inherit the thread rewrite the Run method.
2) Implement the Runnable interface and implement the Run method.
3) Implement the callable interface and override the call method.

What is the difference between the 27.run method and the Start method: The Start method starts a thread and completes the actual operation by the Run method, and if the run method of the thread class is called directly, it is called as a normal function, and the program is still a thread.

28:sleep method and wait method yo what difference:
The Sleep method is the method that causes the thread to pause for a period of time, and wait is the method that causes the thread to pause execution.
1) The principle is different: Sleep is the thread class static method, is the thread to control its own process, and the wait method is the method of the object class, used for communication between threads, this method will make the object lock process Wait, know other threads call notify method
2) The mechanism for locking is different: The wait method causes the thread to release the lock that his lock occupies.
3) Use different areas: The wait method must be used in either the synchronization control method or the synchronous statement block. Sleep must catch an exception.

29:JDBC General steps to access a database:
1) load the JDBC drive.
2) load the JDBC driver.
3) Establish a database connection to get the connection object.
4) Establish statement object or PreparedStatement object.
5) Execute the SQL statement.
6) Access result set Results object.
7) Close the object in turn to release the resource.

Advantages of 30.PreparedStatement objects:
1) More efficient (the command will be compiled and parsed by the database, placed in the command buffer, the next time the buffer will be parsed directly in the command, will not be compiled again).
2) better readability and maintainability of the code.
3) better security.

Details! Focus! Easy wrong point! --Interview Java Basics (II.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.