Java Basics-2

Source: Internet
Author: User
Tags thread class try catch

The size of the nine basic data types, as well as their encapsulation classes.
Basic Type size (bits) bytes Minimum Value Maximum Value Encapsulation Class
Boolean - 1 - - Boolean
Byte 8 1 -128 127 Byte
Char 16 2 Unicode 0 Unicode 2^16-1 Character
Short 16 2 -2^15 2^15-1 Short
Int 32 4 -2^31 2^31-1 Integer
Float 32 4 Float
Double 64 8 Double
Long 64 8 -2^63 2^63-1 Long
void - - - Void
Can switch use string to make arguments?

JDK1.7 is only supported for int or char

JDK1.7 starts to support string

JDK1.5 started supporting Enum classes

The difference between equals and = =

the "= =" is used for comparison of the base data type to determine whether the reference points to the same fast address of heap memory.

equals is used to determine whether two variables are a reference to the same object, that is, whether the contents of the heap are the same, and the return value is a Boolean type.

You can use the Equals method to detect the equality of two strings.

You must not use the = = operator to detect the equality of two strings! = = is used to determine whether two strings are placed in the same position.

If the virtual machine always shares the same string, you can use the = = operator to detect equality. But actually only string constants are shared, and the results of operations such as + or substring are not shared.

What are the common methods of object?
    1. Equals method

The Equals method in the object class is used to detect whether an object is equal to another object.

    1. Hashcode method

This method is used for hash lookups, which reduces the number of equals used in lookups, overriding the Equals method, which generally overrides the Hashcode method. This method is used in some collection with hash functions.

    1. ToString Method

Used to return a string representing the value of an object.

Java four kinds of references, soft and weak, used to the scene
    1. Strong references

Strong references are the most commonly used references. If an object has a strong reference, the garbage collection period will never reclaim it.

    1. Soft references

If an object has only soft references, enough memory space is available, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.

    1. Weak references

The difference between a weak reference and a soft reference is that an object with only a weak reference has a more ephemeral life cycle.

As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not.

However, because the garbage collector is a low-priority thread, it is not as quick to find objects that have only weak references.

If you want to refer to an object, but this object has its own life cycle, you do not want to intervene in the life cycle of this object, you are using weak references.

    1. Virtual reference

A virtual reference does not determine the life cycle of an object, and if an object holds only a virtual reference, it can be reclaimed by the garbage collector in any fit, just as there is no reference.

Summarize:

The level of Java 4 references is from highest to lowest:

Strong "soft" weak "virtual

The role of Hashcode

The existence of hashcode is mainly used to find the shortcut, such as Hashtable,hashmap, etc., Hashcode is used in the hash storage structure to determine the storage address of the object

The difference between ArrayList, linkedlist and vectors

ArrayList is essentially an array, and when more elements are added to the ArrayList, their size grows dynamically, and the inner elements are accessed through get and set methods. is not thread-safe.

LinkedList is a doubly linked list, so it is superior to the array form of ArrayList when deleting and adding elements, but is weaker than ArrayList in Get and set;

Vectors are almost the same as ArrayList, but vectors are thread-safe, and when more elements come in, the vector is twice as much space per request, while ArrayList increases by 50% for size each time.

The difference between String, StringBuffer and StringBuilder

String is an immutable class

StringBuffer is a mutable class

StringBuilder is not thread-safe

In terms of efficiency, StringBuilder highest, stringbuffer second, string lowest

If the amount of data to be manipulated is small, precedence should be given to the string class

If you are manipulating large amounts of data on a single thread, you should prioritize the StringBuilder class

If you are manipulating large amounts of data under multiple threads, you should prioritize the StringBuffer class.

Features and usage of MAP, Set, List, Queue, stack
    • Map

The object that the key maps to the value. A map cannot contain duplicate keys, and each key can be mapped to at most one value.

Some mapping implementations can explicitly guarantee their order, such as the TreeMap class, while others do not guarantee the order, such as the HashMap class.

In the map element, you can extract the key sequence, the value sequence, separately.

Use Keyset () to extract the key sequence and generate a set for all keys in the map.

Use values () to extract the value sequence and generate a collection for all values in the map.

Why one is set and one is collection. Because key is unique, value allows for repetition.

    • Set

A collection that does not contain duplicate elements.

Do not randomly access the contained elements

Only one-way traversal can be implemented with Lterator

Set has no synchronization method

    • List

Random access to contained elements

Elements are ordered.

Element can be deleted at any location

Element position unchanged no matter how many times it is accessed

Allow repeating elements

Implement one-way traversal with iterator, and also use Listiterator to implement bidirectional traversal

    • Queue

Advanced First Out

Use Offer () to add elements

Use poll () to get and move out of an element

Peek () method view or use front-end elements

Queue implementations typically do not allow the insertion of a NULL element

    • Stack

Last in, first out

Stack inherits from Vector, is synchronous

Provides push, pop, peek, empty methods

    • Usage

If it involves operations such as stacks, queues, etc., you should consider using the list

For quick insertions, delete elements, you should use LinkedList

If you need to quickly randomly access elements, you should use ArrayList

If a single-threaded environment, consider non-synchronized classes, high efficiency.

The difference between HashMap and Hashtable

Key differences: Thread safety, synchronization, speed

    1. HashMap is almost equivalent to Hashtable, except that HashMap is not synchronous and can accept null

      The difference between HashMap and Concurrenthashmap, HashMap's underlying source code

The essence of HashMap is an array-linked list. The hash value is obtained according to Key, and then the array subscript is computed, and if multiple keys correspond to the same subscript, the linked list is used to string up the new inserted in front.

Concurrenthashmap on the basis of HashMap, the data is divided into multiple segment, the default 16, and then each operation on a segment lock, to avoid the possibility of multi-line lock, improve concurrency efficiency.

HashMap is a entry array, entry array contains the keys and values, where next is also a entry object, when the hash conflict, form a linked list.

staticclassimplements Map.Entry<K,V> {         final K key;         V value;         Entry<K,V> next;         finalint hash;           /**           * Creates new entry.           */         Entry(int h, K k, V v, Entry<K,V> n) {             value = v;             //hash值冲突后存放在链表的下一个             key = k;             hash = h;         }          .........     }

HashMap put method for storing data

  PublicVput(K key, V value) {if(Key = =NULL)//If the key is null, call Putfornullkey (value)              return Putfornullkey(value);inthash =Hash(Key.hashcode());//The hash code is calculated according to the hashcode of the key          inti =indexfor(hash, table.)length); for(entry<k,v> e = table[i]; E! =NULL; E = e.Next) {//Handle conflict, if the hash value is the same, then store it in that location with the linked listObject K;if(E.Hash= = Hash && (k = e.Key) = = Key | | Key.equals(k))) {//overwrite and return old value if key is the sameV OldValue = e.value; E.value= value; E.recordaccess( This);returnOldValue; }} modcount++;AddEntry(hash, key, value, I);return NULL; }

When we put the element into the HashMap, it is worthwhile to place the element in the array (i.e. subscript) according to the hash of the key, and then we can put the element in the corresponding position, if there are already other elements in the position of the element, Then the elements in the same seat will be stored in the form of a list, and the newly added drop-off list header, which was previously added, is placed behind.

When a get element is obtained from a hashmap, the hash value of the key is computed first, an element in the corresponding position in the array is found, and the required element is found in the linked list of the corresponding position through the Equals method of key.

If there is no key that is the same as key, call the AddEntry method to create a entry object:

voidaddEntry(intint bucketIndex) {         Entry<K,V> e = table[bucketIndex];    //如果要加入的位置有值,将该位置原先的值设置为新entry的next,也就是新entry链表的下一个节点         new Entry<>(hash, key, value, e);         if//如果大于临界值就扩容             resize(2 * table.length//以2的倍数扩容     }

Scaling data

voidresize(int newCapacity) {         Entry[] oldTable = table;         int oldCapacity = oldTable.length;         if (oldCapacity == MAXIMUM_CAPACITY) {             threshold = Integer.MAX_VALUE;             return;         }          new Entry[newCapacity];         transfer(newTable);//用来将原先table的元素全部移到newTable里面         table = newTable;  //再将newTable赋值给table         threshold = (int)(newCapacity * loadFactor);//重新计算临界值     }
The difference between TreeMap, HashMap and Lindedhashmap. Collection package structure, and the difference between collections. Do you have return,finally in Try Catch finally,try?
    1. No exception in try and return in try

Try---finally---return

    1. There is an exception in try with return in try

Try---Catch---finally---return

In short, finally always executes

    1. Excption with the error packet structure. Oom What situation you have encountered, SOF what you have encountered.
    2. Java object-oriented three features and meanings.
The meanings and differences of override and overload
    • Override (Override)

Overrides are subclasses that rewrite the implementation of methods that allow access to the parent class.

Neither the return value nor the formal parameter can be changed. That is, the shell does not change, overriding the intrinsic implementation.

The benefit of overriding is that subclasses can define their own behavior as needed.

 Public classLIFTOFF { Public Static void Main(String args []) {Animal a=New Animal(); Animal B =New Pig(); A.Eat(); B.Eat(); }    }classanimal{ Public void Eat() {System. out.println("Animal eat xx"); }    }classPigextendsanimal{ Public void Eat() {System. out.println("Pig eat Siliao"); }    }
Animal eat xx pig eat siliao

Rewrite rule:

The argument list must be exactly the same as the overridden method (that is, the override cannot add a write method and cannot add parameters.) )

The return type must be exactly the same as the return type of the overridden method

The Member method of the parent class can only be overridden by his subclasses

A method that is declared final cannot be overridden

A method declared as static cannot be overridden, but can be declared again.

Construction method cannot be overridden

    • Overloading (overload)

Overloading is in the same class, the method has the same name, the parameters are different, the return type can be the same or different methods.

Each overloaded method must have a unique list of parameter types.

The overloaded method must change the parameter list, the overloaded method can change the return type, the overloaded method can change the access modifier, the method can be overloaded in the same class or in a subclass.

   Public classLIFTOFF { Public int Test() {System. out.println("Overload1");return 1; } Public void Test(intA) {System. out.println("Overload1"+ a); } PublicStringTest(String a1, String A2) {System. out.println("Overload1"+ A1+A2);returnA1; } Public Static void Main(String args []) {LIFTOFF t=New LiftOff(); System. out.println(T.Test()); T.Test(2); System. out.println(T.Test("ASD","Erf")); }    }
Overload11Overload12Overload1asderfasd

Overloading and overriding differences:

overloaded Method (overload) override Method (override)
Parameter list Must be modified Can't change
return type can modify Can't change
Abnormal can modify can be reduced or deleted, cannot throw new
Access modifiers can modify Limit can only be lowered and cannot be changed to a higher limit

Limits are low to high: public, protected, private

The difference between interface and abstract class

If a class contains abstract methods, then this class is an abstract class. Class or method declaration is abstract

Interface refers to a collection of methods, all methods in the interface have no method body, the interface is implemented by the keyword interface.

interface and the same point of an abstract class:

    1. Cannot be instantiated
    2. The implementation class of an interface or a subclass of an abstract class can only be instantiated by implementing a method in an interface or abstract class.

Different points:

    1. An interface is defined only and its methods cannot be implemented in an interface, and only the classes that implement the interface can implement the methods defined in the interface, whereas abstract classes may be defined and implemented, i.e. their methods can be implemented in an abstract class.
    2. Interfaces need to be implemented (with implement), but abstract classes can only be inherited (with extends), a class may implement multiple interfaces, but a class can only inherit an abstract class, so the use of interfaces can indirectly achieve the purpose of multiple inheritance.
    3. The interface emphasizes the implementation of a particular function, "has-a"; abstract class emphasizes the affiliation, "Is-a"
    4. The member variables defined in the interface are default to public static final, can only have static data members that cannot be modified, and must be assigned values, so the member methods are public,abstract and can only be modified by these two keywords. Abstract classes can have their own data member variables, or they can have non-abstract member methods, and the member variables in the abstract class defaults to default and can of course be defined as private,protected,public. Therefore, when the function needs to accumulate, with the abstract class, do not need to accumulate when using the interface.
    5. Interfaces are used to implement more commonly used functions for later maintenance; Abstract classes are more inclined to act as a public class role and do not apply to re-modifying internal code later.
The difference between static class and non static class The implementation principle of Java polymorphism implements two methods of Multithreading: Thread synchronization with runable threads: sychronized, Lock, Reentrantlock level of Lock: Method Lock, Object lock, Class lock
    • Java中锁的机制

Synchronized requires a reference object as the lock object when the code block is decorated.

When modifying a method, the default is the object that is the current object as a lock.

When modifying a class, the default is the current class object as the lock object.

Thread synchronization methods: Sychronized, lock, Reentrantlock analysis

    • Method Lock (Synchronized decoration method)

Declare the Synchronized method by adding the Synchronized keyword to the method declaration.

    • Object Lock (Synchronized decoration method or code block)

When a synchronized method or synchronized block in an object calls this object's synchronization methods or enters its synchronization area, it must first obtain an object lock, how this object's object lock has been occupied by other callers, you need to wait for this lock to be released. (method locks are also object locks)

Write a producer consumer model. Threadlocal's design concept and role. ThreadPool usage and advantages. Concurrent other things in the bag: Arrayblockingqueue, Countdownlatch and so on. The difference between wait () and sleep ()

They're all a way to get threads to pause execution.

Difference:

    1. Different principles. Sleep () is a static method of the thread class, and the Wait () method is a method of the object class.
    2. The processing mechanism for locks is different. Sleep is not put, wait is released.
    3. Use different areas
    4. Sleep () must catch an exception, wait () does not require
foreach compares with normal for loop efficiency with Java IO and NiO. The function and principle of reflection

The reflection mechanism enables the loading of classes at run time, thereby increasing the flexibility of the program.

Function:

    1. Gets the class to which an object belongs;
    2. Gets all the member variables and methods of a class;
    3. Creating objects at run time
    4. Methods for invoking objects at run time
There are several ways in which Java creates objects
    1. Instantiating an object with new
    2. Creating an object from a reflection mechanism
    3. Clone ()
    4. How to Deserialize
Common features of generics, List

Java Basics-2

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.