Common minor problems in Javaabc-java

Source: Internet
Author: User
Tags class definition modifiers

Welcome to my repo and I co-editor: Https://github.com/archimekai/JavaABC

Common minor problems in JAVA Abc:java

Note: Jdkapi document (http://docs.oracle.com/javase/8/docs/api/index.html or download CHM format from Http://cf.pku.cn/tds/java)
The source code of the JDK (typically in C:\Program files\java\jdk1.8.0\src.zip)

-–java.lang.object Class-
    1. Is there a difference between equals and = =?

      There is a difference

      The = = Operation compares the values of two variables for equality. For a base variable type, it compares the values of two variables for equality. For reference variable types, it returns whether two references are equal, that is, whether the addresses in the heap they point to are the same, or whether the contents of the stack are the same.

      The Equals method compares the contents of the objects referenced by two variables, that is, whether the contents of the heap are the same.

      For basic variable types, the result of equals and = = is no different.

    2. What is the modifier in front of its hashcode and clone?

      native

      nativeThe keyword describes its modification as a native method that is implemented not in the current file, but in other languages such as C, C + +.

    3. What does its ToString () return?

      StringString

      Specifically, the method in object toString() returns the class name and the hashcode of the instance displayed in 16 binary

    4. What does its constructor and finalize () do?

      Nothing has been done in the constructor.

      finalize()Did nothing in it.

-–java.lang.class Class-
  1. Why is it that class classes cannot be inherited

    The class class has a keyword in its definition that final makes it impossible for class classes to be inherited.

  2. Why can't we say new Class ()?

    Why is that?

    Because the only constructor method in class private Class(ClassLoader loader) is a private method, it cannot be called.

  3. What process was executed in forname ()?

    Use the given class loader and class name to get the corresponding Class object. forName0()This private native method is called to complete the task.

  4. What does toString () return?

    Returns a string that, if it is an interface, “interface” outputs getName() the return value of +, or if it is a primitive type, returns a + if it is a getName() normal class “class” getName() .
    getName()Returns a member from classname

  5. What was executed in newinstance ()?

    newInstance()Returns a new instance of the type represented by class object.
    The following steps are performed:
    First, if System.getsecuritymanager () is non-null, use checkmemberaccess to check the accessibility of the member.

    And we need the great God to guide you here,

    Then, if there is no already cached constructor, check if it is exactly class.class, and if so, throw an exception because class is not designed to be constructed IllegalAccessException . After the check is passed, go to get Member.declared's constructor and deposit it Cachedconstructor

    It is now ensured that the constructor has been cached, then examined using the reflection mechanism, and then called the Newinstance method of the constructor.

-–java.lang.string Class-
  1. Why is string immutable? Why not use + = in multiple loops? Which modifier is added with value? What are the values returned by the Replace, append, trim, and so on methods?

    1. Why is string immutable?
      1. Immutable objects can improve the efficiency and safety of the string pool. If an object is immutable, it is only necessary to copy its address when copying the content, and the efficiency of copying the address is usually very high.
      2. immutable objects are safe for multithreading
    2. Why can't I use + =

      Every time in a loop + =, you need to create a new StringBuilder object and change the reference to increase overhead.

      From compiled code, the exact operation of string+ is:

      New StringBuilder ()

      New string.valueof ()

      StringBuilder.

      Stringbuilder.append ()

      Stringbuilder.tostring ()

    3. The modifier added before
    4. value?
      The static modifier is added before its value series function to indicate that the returned object is immutable

      Why does

      return a static string?

    5. What are the values returned by the Replace, append, trim, and so on methods? The
      returns a value of type String .
  2. What formula does the
  3. Hashcode use to compare it with the authentication code of the ID Card, ISBN, and bank card number? The formula used by

    Hashcode is as follows: s[0]*31^ (n-1) + s[1]*31^ (n-2) + ... + s[n-1]
    where n is a string length, s[i ] is an I character in a string.

    • ID: ID Check code is the last one of the ID number, which is calculated as follows:
      1, multiply the previous ID number 17 digits by the different coefficients respectively. The coefficients from first to 17th are: 7 9 5 8 4 2 1 6 3 7 9 5 8 4 2;
      2, adding the result of multiplying the 17 digits and coefficients;
      3, by adding and dividing by 11, to see what the remainder is;
      4, the remainder may have 0 1 2 3 4 5 6 7 8 9 10 This 11 number. The number of the last identity card corresponding to it is 1 0 X 9 8 7 6 5 4 3 2;
    • ISBN calculation Method:
      1. Assume that the first 13 bits of a 15-bit ISBN number (containing '-' symbols) are: 987-7-309-04547;
      2. Location is 12 3-4-567-89 (n) (3)
      . Calculate Weights and s:s=9x1+8x3+7x1+7x3+3x1+0x3+9x1+0x3+4x1+5x3+4x1+7x3 = 117;
      4. Calculates the remainder of the s÷10 m:m = 117 mod = 7;
      5. Calculate the difference between 10-m and n = 10? 7 = 3 (if the value of 10-m is 10, check the code takes 0)
    • Verification Code for the bank card number

    Different points: string of the Hashcode The calculation does not significantly take the remainder, but instead directly takes advantage of the range of the int type value?? The calculation of the hashcode of the
    string takes advantage of the exponentiation operation, which is more complex than the other methods, and less prone to equal conditions.
    not well written here

  4. Does the Equals method determine whether the content is equal or reference equal? What is the comparison of CompareTo?

    The first is to determine if the reference is the same, or if the reference is the same, true otherwise, if the object is of type string, then the content is further compared to the same, and the same case is returned true , otherwise false .
    CompareTo are compared in dictionary order.

  5. The comment of the Intern () method indicates what kind of string must be placed in a pool?

    All "literal string" are in the string pool
    "Literal" represents a string, and the value equals itself. The constant expression evaluates to "literal".

  6. What algorithmic processes are used by their indexof?

    First, determine whether the starting position fromindex is in the legal range, and then, starting from the starting position to iterate through the string (the content is actually stored in the char[]), check whether the character is looked for, if so, return its subscript, if not found in the end, return-1. In addition, if the character you are looking for is ch>=character.min_supplementary_code_point, it is a supplementary character, called indexofsupplementary (int ch, int fromIndex) To find. This function matches characters into high and low positions.

    Why do we have this min_supplementary_code_point?

  7. What kind of exception does the SUBSTRING function throw, and does this exception have to be captured?

    IndexOutOfBoundsException。 This exception is a RuntimeException subclass, so it can not be captured.

    Add: About Exceptions in Java

    Click to view Reference source

    ThrowableThere are two important sub-classes: Exception and error.

      • Error (Error): A bug that the program cannot handle, indicating a more serious problem in running the application. Most errors are unrelated to what the code writer does, and represent a problem with the JVM (the Java virtual machine) that is running the code. For example, the Java Virtual machine runs the error (virtual Machineerror) and OutOfMemoryError occurs when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread. These errors indicate that the failure occurred on the virtual machine itself, or when the virtual machine attempted to execute the application, such as a Java Virtual machine run error (virtual Machineerror), a class definition error (NOCLASSDEFFOUNDERROR), and so on. These errors are not available because they are outside the control and processing power of the application and are mostly not allowed when the program is running. For a well-designed application, even if it does, it should not be an attempt to deal with the anomalies that it causes. In Java, errors are described by the subclasses of the error.
      • Exception (Exception): is an exception that the program itself can handle. The Exception class has an important subclass runtimeexception. The RuntimeException class and its subclasses represent errors thrown by the JVM common operation.

    Java exceptions (including exception and error) are also categorized as exceptions (checked exceptions) and non-checked exceptions (unchecked exceptions).

      • can check exceptions (compiler requirements must be disposed of exceptions): the correct program in operation, it is easy to appear, reasonable tolerance of abnormal conditions. Although the abnormal condition can be checked, it can be predicted to some extent, and in the event of such abnormal situation, it must be handled in some way. In addition to RuntimeException and its subclasses, other exception classes and their subclasses belong to the exception-checking. This exception is characterized by the Java compiler checking it, that is, when such an exception can occur in a program, either by capturing it with a try-catch statement or by declaring it with a throws clause, or the compilation will not pass.

      • Exception not checked (compiler does not require forced disposition of exceptions): Includes run-time exceptions (RuntimeException with its subclasses) and errors (Error)

    Exception can also be classified as run-time exceptions and non-runtime exceptions (compilation exceptions).

      • Run-time Exceptions: both the RuntimeException class and its subclass exceptions, such as nullpointerexception (null pointer exception), indexoutofboundsexception (subscript out-of-bounds exception), and so on, these exceptions are not checked for exceptions, You can choose to capture or not handle the program. These exceptions are usually caused by a program logic error, and the program should avoid this kind of exception as much as possible from a logical point of view. A run-time exception is characterized by the Java compiler not checking it, that is, when such an exception can occur in a program, even if it is not captured with the Try-catch statement, it is not thrown with the throws clause declaration, and it is compiled.
      • Non-runtime exception (compile exception): is an exception other than RuntimeException, and the type belongs to the exception class and its subclasses. From the point of view of the program syntax is the exception that must be handled, and if not handled, the program cannot be compiled through. such as IOException, SqlException, etc.
  8. What kind of class is used by the concat function, and what is the method that finally calls the class?

    Arrays.copyOf()methods (Array.newinstance, new object[]) and methods were used (eventually called) String.getChars() , which called the System.arraycopy () method

  9. What classes are borrowed from ReplaceAll to achieve this? valueof and format?

    • It is Matcher implemented by borrowing classes, and Matcher is obtained through the compile () method of the Pattern class.
    • ValueOf uses the ToString () method of the object class and many constructors for the string class.
    • The format class uses the format method of the formatter class
-–java.lang.stringbuilder and Abstractstringbuilder class-
    1. How many characters is the initial memory of StringBuilder?

      16

    2. How much does the Expandcapacity () method extend on the original basis?

      Old capacity + 2, or expandcapacity () expands capacity to (old capacity + 1) * *

    3. What are the benefits of the return values of the insert (), append (), delete () methods, and so on?

      Returns StringBuffer. Benefits: Ensure a uniform type in the operation, StringBuffer to a mutable class, and use the StringBuffer class to help reduce the overhead of the system.

      But I don't really understand

-–java.lang.integer Class-
  1. What modifiers are added to the value field? Why is it that integer is immutable?

    static。 Because its members are final types.

    It seems to start from how to judge immutable, how to answer it?

  2. What modifiers are used for constants such as Max_value?

    @Native public static final。 Static indicates that it is quiescent, and final indicates that it cannot be modified after life. @Native indicates that the value should be obtained from the form Native code.

  3. What method does toString (int i) use to speed up its calculations?

    This method does not directly call ToString (int i, int radix), but instead writes the algorithm separately. The key is to call the GetChars function, when I is greater than or equal to 65536, each processing two bits, when I is small, the use of another fast algorithm. To further speed up, the char type ' 0 ' to ' 9 ' is also pre-stored.

  4. What kind of exception does the parseint function throw, and does this exception have to be captured?

    NumberFormatException。 It is a RuntimeException subclass, so it can not be captured.

  5. What is the role of Integercache? valueOf (int i) indicates what range of int will be cached after boxing?
    • Integercache will IntegerCache.low store the IntegerCache.high integer objects (including endpoints) in advance to save memory and reduce the overhead of creating and destroying objects.
    • In general, integers within the range of 128 to 127 are cached. Exactly, is the IntegerCache.low IntegerCache.high value between the to.
  6. How does the hashcode count?

    Returns the numeric value of an integer directly.

-–java.lang.math Class-
    1. A few methods are native methods.

      such as, sin() cos() ,, etc., tan() sqrt() , cbrt() etc...

-–java.util.random Class-
    1. What did the constructor initialize with?

      The constructor is initialized with a seed of a long integer type, specifically, used to obtain the seed when the parameterless constructor is called seedUniquifier() ^ System.nanoTime() .

    2. What is the formula for a random number?

      When a new random number is generated, the seed is updated with the following value: And (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1) then returned (int)(seed >>> (48 - bits)) as the resulting random number.

-–java.math.biginteger Class-
    1. To determine if a large number is likely to be prime, there are two passxxx functions, what are the differences?

      • private boolean passesMillerRabin(int iterations, Random rnd)
      • private boolean passesLucasLehmer()
    2. What is internally used to represent a large integer

      Array of integers

      Is it?

-–java.util.arrays Class-
    1. Sort (int[]) is what sort method to use?

      Internally called DualPivotQuicksort.sort() , its algorithm is Yaroslavskiy, Jon Bentley, and Joshua Bloch proposed Dual-pivot quicksort algorithm. For the common (One-pivot) quicksort algorithm, many data sets cause its complexity to be increased to O (n^2), but in most cases the algorithm maintains the complexity of O (n log (n)).

    2. Sort (object[] a) is what sort method to use?

      For the stability, adaptability, recursive merge sorting algorithm. Also, when the input sequence is basically ordered, the algorithm requires only about n comparisons.

      Suitable for merging two sorted arrays.

      Internal invocation: In two cases, if the user requires the use of legacymergesort, it is called legacyMergeSort() , otherwise it is used ComparableTimSort.sort() .

-–java.util.arraylist Class-
    1. How many times per capacity increase can be seen in the Code of Grow ()?

      Increase to 1.5 times times the original.

-–java.util.vector Class-
    1. How many times per capacity increase can be seen in the Code of Grow ()?

      If not specified capacityIncrement , each increment is twice times the original. Otherwise, increase the capacityIncrement space each time.

      Why do vectors and ArrayList have different growth multiples?

-–java.util.stack Class-
    1. What class does the Stack class inherit?

      VectorClass

    2. What does push () do with pop ()?

      • push()A method that calls the vector directly addElement() .
      • pop()The save is left until the Vector.peek() last return, and then the method is called removeElementAt(len - 1) .
-–java.util.hashtable Class-
    1. What are the 4 fields in the Inner class entry?

          finalint hash;    final K key;    V value;    Entry<K,V> next;
-–java.util.treemap Class-
    1. The code in ContainsKey () shows what the condition is for the object to be found. If the hashcode of a key object is changed (as it is calculated with the content), will the key object be found?

      getEntry(key)The return is not null . In the getEntry() case of the two cases, if there is a comparator, call Getentryusingcomparator (key), otherwise, use K.compareto () to compare until an equal key value is found, if it cannot be found, it returns NULL. Getentryusingcomparator is a similar algorithm, but the comparison function in which it is called is compare (t,t).

      Whether it can be found depends on whether the comparison function in question is based on hashcode. Since TreeMap stores data in the form of an ordered list, it may not be possible to find an existing element if the hashcode changes, causing the original sort to fail.

      Is the explanation right here?

-–java.util.treeset Class-
    1. What objects are used to achieve the bottom of treeset?

      TreeMap

-–java.util.timer Class-
    1. How does the bottom of the timer execute repeatedly?

      The Sched () private method was called, and a queue was used in the method to implement recurrence by adding and extracting task execution time in the queue.

      I haven't read it yet.

-–javax.swing.timer Class-
    1. Where is the bottom of the timer calling Swingutilities.invokelater?

      void post()called in.

Supplementary questions

Java.util.Arrays

  1. From the Copyof method, how do I instantiate an array with generics?

    @SuppressWarnings("Unchecked") Public Static<T> t[]copyOf(T[] Original,intNewlength) {return(t[]) copyOf (original, Newlength, Original.getclass ());} Public Static<T,U> t[]copyOf(U[] Original,intNewlength, class<? Extends T[]> NewType) {@SuppressWarnings("Unchecked") t[] Copy = ((object) NewType = = (object) object[].class)? (t[])NewObject[newlength]: (t[]) array.newinstance (Newtype.getcomponenttype (), newlength); System.arraycopy (Original,0, copy,0, Math.min (Original.length, newlength));returncopy;}

    Forced type conversions are required. Specifically, when you create an array, compare, (object) NewType = = (object) Object[].class, or, if it is the same, convert the new array directly to t[], otherwise call array.newinstance ( Newtype.getcomponenttype (), newlength), and then do the coercion type conversion.

    Need great God's guidance

Common minor problems in Javaabc-java

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.