Java (3), java (2)
- Short a = 1; a = a + 1; is there a mistake? Short a = 1; a + = 1; is there a mistake?
For short a = 1; a = a + 1; because the expression type is automatically increased during the + 1 operation, the result is int type. When the short Type a is copied, the compiler will report errors that require forced replacement of types.
For short a = 1; a + = 1; Because ++ = is an operator specified by the java language, the java compiler will perform special processing on it, so it can be compiled correctly.
- What is the difference between static variables and instance variables?
Syntax definition difference: the static keyword must be added before the static variable, but not before the instance variable.
Differences during program running: instance variables belong to the attributes of an object. You must create an instance object. Only instance variables in the instance can be allocated space to use this instance variable. Static variables do not belong to a certain instance object but belong to a class, so they are also called class variables. As long as the program loads the class bytecode, no instance object needs to be created, static variables are allocated space, and static variables can be used. In short, instance variables can be used only after an object is created. Static variables can be referenced directly by class names.
For example, for the following program, no matter how many instance objects are created, only one staticVar variable is always assigned, and each time an instance object is created, this staticVar will add 1; however, each time an instance object is created, an instanceVar will be assigned, that is, multiple instanceVar may be allocated, and each instanceVar value is added only once.
public class VariantTest{ public static int staticVar = 0; public int instanceVar = 0; public VariantTest(){ staticVar++; instanceVar++; System.out.println(“staticVar=” + staticVar + ”,instanceVar=” + instanceVar); }}
- Can I modify a variable using the final keyword, whether the reference cannot be changed, or the referenced object cannot be changed?
When you use the final keyword to modify a variable, it is suggested that the variable cannot be changed, and the content in the object to which the referenced variable points can still be changed.
For example, for the following statement:
final StringBuffer strA=new StringBuffer("immutable");
Run the following statement to report compilation errors:
strA=new StringBuffer("");
However, the following statement can be compiled:
strA.append(" broken!");
When defining the parameters of a method, someone may want to use the following form to prevent the method from modifying the passed parameter object:
public void method(final StringBuffer param){ }
In fact, this cannot be done. In this method, you can add the following code to modify the parameter object:
param.append("abc");
- Differences between final, finally, and finalize.
Final is used to declare attributes. Methods and classes indicate that attributes are unchangeable, methods cannot be overwritten, and classes cannot be inherited.
Finally is a part of the structure of the exception handling statement, indicating that it is always executed.
Finalize is a method of the Object class. This method is called when the garbage collector is executed. It can overwrite this method to collect other resources during garbage collection, for example, close a file.
- What is the difference between abstract class and interface?
The class that declares a method rather than implementing it is called abstract class. It is used to create a class that reflects some basic behaviors and declare a method for this class, however, this class cannot be implemented in this class. You cannot create an abstract instance. However, you can create a variable whose type is an abstract class and point it to an instance of a specific subclass. Abstract constructors or abstract static methods are not allowed. The subclasses of Abstract classes provide implementation for all Abstract methods in their parent classes. Otherwise, they are also Abstract classes. Instead, implement this method in the subclass. Other classes that know their behavior can implement these methods in the class.
An interface is a variant of an abstract class. All methods in the interface are abstract. Multi-inheritance can be achieved by implementing such an interface. All methods in the interface are abstract, and none of them have a program body. The interface can only define static final member variables. The implementation of an interface is similar to that of a subclass, except that the implementation class cannot inherit behaviors from the interface definition. When a class implements a special interface, it defines (to be given by the program body) all the methods of this interface. Then, it can call the interface method on any object that implements the interface class. Because there is an abstract class, it allows the interface name as the type of the referenced variable. Normally, dynamic Association editing will take effect. The reference can be converted to the interface type or from the interface type. The instanceof operator can be used to determine whether the class of an object implements the interface.
- The difference between HashMap and Hashtable.
HashMap is a lightweight Implementation of Hashtable (non-thread-safe implementation). They all complete the Map interface. The main difference is that HashMap allows null key values ), because of non-thread security, the efficiency may be higher than that of Hashtable.
HashMap allows null as the key or value of an entry, whereas Hashtable does not.
HashMap removes the contains method of Hashtable and changes it to containsvalue and containsKey. The contains method is easy to misunderstand.
Hashtable inherits from the Dictionary class, while HashMap is an implementation of the Map interface introduced by Java1.2.
The biggest difference is that the Hashtable method is Synchronize, but HashMap is not. When multiple threads access Hashtable, they do not need to implement synchronization for their own methods, hashMap must provide external synchronization for it (if it is ArrayList: List lst = Collections. synchronizedList (new ArrayList (); For HashMap: Map map = Collections. synchronizedMap (new HashMap ());).
The hash/rehash algorithms used by Hashtable and HashMap are roughly the same, so there is no big difference in performance.
- Is there any memory leakage in Java? Please briefly describe it.
Yes. For example:
Int I, i2; return (i-i2); // when I is a positive number that is big enough, and i2 is a negative number that is big enough. The result may cause overflow and errors.
- What is the difference between sleep () and wait?
Sleep () is a Thread-like Thread method. As a result, this Thread suspends the execution for a specified time and gives the execution opportunity to other threads. However, the monitoring status remains unchanged and will be automatically restored, calling sleep does not release the object lock.
Wait () is an Object method. Calling the wait method for this Object causes this thread to discard the Object lock and enter the waiting lock pool for this Object, this thread enters the object lock pool only after the notify method (or notifyAll) is issued for this object to prepare for obtaining the object lock to enter the running state.
- The differences between HashMap, TreeMap, and LinkedHashMap in Java.
Java defines an interface java. util. Map for ing in the data structure. It has four implementation classes: HashMap, Hashtable, LinkedHashMap, and TreeMap.
Map is mainly used to store the key-value pairs and obtain values based on the keys. Therefore, duplicate keys are not allowed (repeated overwrites), but repeated values are allowed.
HashmapIs the most commonly used Map. It stores data based on the HashCode value of the key, and can directly obtain its value based on the key, with fast access speed and time elapsed, the order in which data is obtained is completely random. HashMap allows a maximum of Null keys for one record and Null values for multiple records. HashMap does not support thread synchronization, that is, multiple threads can write HashMap simultaneously at any time; data inconsistency may occur. If synchronization is required, you can use the synchronizedMap method of Collections to synchronize HashMap or use ConcurrentHashMap.
HashtableSimilar to HashMap, It inherits from the Dictionary class. The difference is that it does not allow null keys or values to be recorded. It supports thread synchronization, that is, only one thread can write Hashtable at any time, as a result, Hashtable is slow in writing.
LinkedHashMapThe record insertion sequence is saved. When Iterator is used to traverse the LinkedHashMap, the first record is certainly inserted first. You can also use parameters to sort the records by the number of times of application during construction. It is slower than HashMap during traversal, but in some cases, when the HashMap capacity is large and the actual data is small, the traversal may be slower than LinkedHashMap, because the traversal speed of LinkedHashMap is only related to the actual data and has nothing to do with the capacity, and the traversal speed of HashMap is related to its capacity.
TreeMapThe SortMap interface can sort the records stored by the key. By default, the key value is sorted in ascending order. You can also specify the sort comparator. When you use Iterator to traverse the TreeMap, the obtained records are sorted in ascending order.
Generally, HashMap is used most often. The key-value pairs stored in HashMap are random when they are retrieved. It stores data based on the key's HashCode value, you can directly obtain its value based on the key, with fast access speed. HashMap is the best choice for inserting, deleting, and locating elements in a Map.
TreeMap obtains the sorted key-value pairs. However, if you want to traverse keys in the natural or custom order, it is better to use TreeMap.
LinkedHashMap is a subclass of HashMap. If the output sequence is the same as that of the input, you can use LinkedHashMap to implement it. It can also be arranged in the read order, as it can be applied in the connection pool.
- What are the storage performance and features of ArrayList, Vector, and shortlist?
1). ArrayList
The object is saved in the array format. This method places the object in a continuous position, so the biggest drawback is that it is very troublesome to insert and delete objects.
Shortlist
Objects are stored in an independent space and the index of the next link is saved in each space. However, the disadvantage is that it is very troublesome to search for objects, starting with the first index.
2). ArrayList and Vector
All data is stored in arrays. The number of elements in this array must be greater than the actual storage space for element addition and insertion. They allow the element to be indexed directly by serial number, however, inserting data elements involves memory operations such as element movement, so index data is fast and data insertion is slow.
3). VectorThe sychronized method (thread security) is used, so the performance is worse than that of ArrayList ..
4). Upload listThe two-way linked list is used to store data. The index data requires forward or backward traversal. Therefore, the index data is slow. You only need to record the items before and after data insertion, therefore, the insert speed is fast.
- Can the switch statement be applied to byte, long, and String?
In switch (expr1), expr1 can only be an Integer expression or enumeration constant. An Integer expression can be of the int basic type or Integer packaging type, because, byte, short, char can be implicitly converted to int. Therefore, these types and their packaging types are also acceptable. Obviously, the long and String types do not comply with the switch syntax and cannot be implicitly converted to the int type. Therefore, they cannot be applied to swtich statements.
- The three plan to split a rectangle cake, but one has secretly cut the part of a small rectangle. If only one straight cutting is required, how can the other two cut the remaining parts evenly?
Some may say: just split the cake into two equal parts. However, the upper layer of the cake is cream, and the lower layer only has dry bread, so we are not prepared to use this as one of the answers. If this cake is not cut off, how should we divide it equally? Of course there are many methods, but all the tangent methods have one thing in common, that is, this knife must go through the center of the rectangle. And vice versa. All straight lines passing through the center can divide the rectangle into two parts equally. With this conclusion back to the problem, if a knife passes through the two rectangular centers, the large rectangle ABCD and the small rectangle AGFE can be divided into two parts with the same area, our problem is solved.
I am the dividing line of tiantiao
Reference: http://www.cnblogs.com/liu-qing-hua/p/3877768.html
JAVA interview questions: three answers
1. stack: the stack zone is automatically allocated and released by the compiler, and stores function parameter values and local variable values. The operation method is similar to the stack in the data structure.
2. heap-generally assigned and released by the programmer. If the programmer does not release the heap, it may be recycled by the OS at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.
In C ++, a class is allowed to inherit multiple classes. However, the language after Java is not allowed.
In this way, it is very difficult to inherit multiple classes. So the developer came up with a new method: interface.
An interface can contain the basic content of a variable, constant, and other classes. However, functions in the interface do not allow code setting, which means that the program entry cannot be placed in the interface. It can be understood from the above that interfaces are specially inherited. The meaning of an interface is also inherited. It is the same as the pure virtual function in the abstract class in C ++. It cannot be instantiated.
3. import java. util .*;
Public class Test {
Public static void main (String [] args ){
Int [] list = new int [1000000];
Int I = 0;
For (; I <1000000; I ++ ){
List [I] = I;
}
List [600000] = 90000;
Set set = new HashSet ();
For (I = 0; I <list. length; I ++)
{
If (! Set. add (list [I])
Break ;}
System. out. println (I );
System. out. println ("the same number is" + list [I]);
}
}
How can I start a thread in java? Not just star ()?
There are two ways to create a new execution thread. One way is to declare the class as a subclass of Thread.
Another way to create a thread is to declare a class that implements the Runnable interface.
I know these two types. Haha