Java Pen Questions (5)

Source: Internet
Author: User
Tags comparable finally block

What are the 1.Comparable and comparator interfaces for? List the differences between them.

Java provides a comparable interface that contains only one CompareTo () method. This method can be used to sort two objects in a single order. Specifically, it returns a negative number, 0, a positive number to indicate that the input object is less than, equal to, greater than the already existing object.

Java provides a comparator interface that contains two methods of compare () and Equals (). The Compare () method is used to sort two input parameters, return a negative number, 0, and a positive number indicates that the first parameter is less than, equal to, greater than the second argument. The Equals () method requires an object as a parameter that determines whether the input parameters are equal to comparator. This method returns true only if the input parameter is also a comparator and the input parameter is the same as the current comparator's ordering result.

2. What is the difference between the code identified by line A and line B in the following code fragment?

 Public classconstantfolding {Static Final  intNumber1 = 5; Static Final  intNumber2 = 6; Static intNumber3 = 5; Static intNumber4= 6;  Public Static voidMain (string[] args) {intProduct1 = Number1 * NUMBER2;//Line A           intProduct2 = Number3 * NUMBER4;//Line B     } }

In the code for line A, the value of product is calculated at compile time , and Row B is calculated at run time . If you use the Java anti-compiler (for example, Jd-gui) to decompile the Constantfolding.class file, you will get an answer from the following results.

 Public classconstantfolding{Static Final intNumber1 = 5; Static Final intNumber2 = 6; Static intNumber3 = 5; Static intNumber4 = 6;  Public Static voidMain (string[] args) {intProduct1 = 30; intProduct2 = Number3 *Number4; }}

Constant folding is an optimization technique used by the Java compiler. Because the values of the final variables do not change, they can be optimized. Both the Java anti-compiler and the JAVAP command are a powerful tool for viewing compiled code (for example, bytecode).

3. Can you think of any situation where it would be helpful to look at compiled code in addition to code optimization?

Generics in Java are constructed at compile time, you can understand generics by looking at the compiled class file, or you can view it to solve generic-related problems.

4. Which of the following occurs at compile time, at run time, or both?

  • method Overloading : This occurs at compile time. Method overloading is also known as compile-time polymorphism, because the compiler can choose which method to use based on the type of the parameter.
     Public class {     publicstaticvoid Evaluate (String param1);  // Method #1      Public Static void Evaluate (int param1);   // method #2}
    If the compiler wants to compile the following statement:
    Evaluate ("My Test Argument passed to param1");
    It generates a byte code that calls the # # method, based on the parameters passed in as String constants
  • method Overrides: This occurs at run time. The method overload is called run-time polymorphism because the compiler does not know at compile time and cannot know which method to invoke. The JVM will make a decision when the code is running.
     Public classA { Public intComputeintInput) {//Method #3        return3 *input; }        }  Public classBextendsA {@Override Public intComputeintInput) {//Method #4        return4 *input; }        }
    Compute (..) in sub-category B The Compute method overrides the parent class's (..) Method. If the compiler encounters the following code:
     Public int int arg2)  {     int result = Reference.compute (arg2);}
    The compiler is not able to know whether the type of the passed parameter reference is a or B. Therefore, it is only possible at run time to determine whether to invoke method # or method # #, depending on the type of object assigned to the input variable "reference" (for example, an instance of a or B).
  • generics (also known as type checking): This occurs at compile time. The compiler is responsible for checking the correctness of the type in the program, and then translating or rewriting the code that uses generics into non-generic code that can be executed on the current JVM. This technique is called "type erase". In other words, the compiler erases all type information in the angle brackets to ensure compatibility with version 1.4.0 or earlier versions of the JRE.
    New Arraylist<string> (10);
    After compiling it became:
    New ArrayList (10);
  • annotations (Annotation): You can use annotations at run time or compile time.
     Public class extends A {   @Override    publicint compute (int input) {      // Method #4        return 4 * input;    }       }
    @Override is a simple compile-time annotation that can be used to catch errors similar to writing ToString () to ToString () in a subclass. In Java 5, user-defined annotations can be processed at compile time with the annotation processing tool (Anotation process tool--apt). To Java 6, this feature is already part of the compiler.
     Public class mytest{    @Test     publicvoid  testemptyness () {         Org.junit.Assert.assertTrue (GetList (). IsEmpty ());     }       Private List getList () {        //implemenation goeshere     }}
    @Test is an annotation that the JUnit framework uses to determine which of the methods of the test class to invoke at run time by reflection.
    @Test (timeout=100)publicvoid  testtimeout () {    while(True );   // Infinite Loop}
    If the run time exceeds 100ms, the test case above will fail.
    @Test (expected=indexoutofboundsexception.  Class)publicvoid  testoutofbounds () {       new Arraylist<object> (). Get (1);}
    If the above code does not throw a indexoutofboundsexception at run time or throws a different exception, the use case will fail. User-defined annotations can be handled at run time through the new annotatedelement and "Annotation" element interfaces in the Java Reflection API.
  • exception (Exception): You can use run-time exceptions or compile-time exceptions.
  • A run-time exception (RuntimeException) is also known as an undetected exception (unchecked exception), which means that the exception does not require a compiler to detect. RuntimeException is the parent class for all exceptions that can be thrown at run time. A method that, in addition to catching an exception, may throw a runtimeexception subclass if it executes, and it does not need to declare the thrown exception with a throw statement.

    For example: nullpointerexception,arrayindexoutofboundsexception, etc.

  • The check exception (checked exception) is the compiler verifies at compile time, and the detection exception is handled through the throws statement or the try{}cathch{} statement block. The compiler parses which exceptions are thrown when executing a method or constructor.
  • aspect-oriented programming (Aspect oriented PROGRAMMING-AOP): Facets can be woven at compile time, at run time, at runtime, or at run time.
  • compile time : compile-time weaving is the simplest way. If you have the code for your app, you can use the AOP compiler (for example, the AJC–ASPECTJ compiler) to compile the source, and then output the class file that was woven into the complete. The process of AOP compilation contains waver calls. The form of a slice can be in the form of a source code or in a binary form. If the facets need to be compiled for the affected classes, then you need to weave them at compile time.
  • post-compilation : This is sometimes referred to as binary weaving, which is used to weave existing class files and jar files. and compile-time weaving in the same way, the slices used to weave can be the source code can also be a binary form, and they can also be woven into the plane.
  • Loading period : This weaving is a binary weave that is deferred until the JVM loads class files and defines classes. To support this weaving method, one or more "weaving classloader (Weaving class loader)" needs to be provided explicitly by the runtime environment or through a "weaving agent" (weaving agent).
  • Runtime: Weaving classes that have been loaded into the JVM
  • Inheritance – occurs at compile time because it is static
  • Agent or combination – occurs at run time because it is more dynamic and flexible.

    5. Can you differentiate between compile-time inheritance and runtime inheritance by using an instance, and what kind of Java support is indicated?

    Inheritance represents the scene in which actions and attributes are passed from one object to another. The Java language itself only supports compile-time inheritance, which is implemented by means of the "extends" keyword to produce subclasses, as follows:

     public  class   Parent { public   String saysomething () { return   "pare    NT is called "; }}  public  class  child extends   Parent {@Override  public String saysomething () { return  super . saysomething () +

    The call to the SaySomething () method of the

    Child class returns "Parent is Called,child is called" because the call to the subclass inherits the "Parenet is called" of the parent class. The keyword "Super" is the method used to invoke the "Parent" class. Run-time inheritance represents building a parent/child class relationship at run time. The Java language itself does not support run-time inheritance, but there is an alternative scenario called "proxy" or "combination", which represents a subclass of a hierarchical object at run time. This simulates the implementation of run-time inheritance. In Java, the typical implementation of an agent is as follows:

     Public class Parent {    public  String saysomething () {          return  ' parent is called ';     Publicclass child  {     public  String saysomething () {           return New Parent (). saysomething () +  ", child is called";    }}

    The child class proxies the invocation of the parent class. Combinations can be implemented in the following ways:

     Public class Child  {     privatenull;        Public Child () {          thisnew  Parent ();     }        Public String saysomething () {          returnthis. parent.saysomething () +  ", Child is called ";    }}

    What are the volatile variables in 6.Java?

    Volatile is a special modifier that can only be used by member variables. Multithreaded operations on member variables are transparent to other threads in the absence of a synchronization class for Java concurrency programs. The volatile variable guarantees that the next read operation will occur after the previous write operation.

    7. What is Futuretask?

    In a Java concurrency program, Futuretask represents an asynchronous operation that can be canceled. It has the methods of starting and canceling operation, whether the query operation is complete and retrieving the result of operation. The result can be retrieved only when the operation is complete, and the Get method will block if the operation has not been completed. A Futuretask object can be wrapped on an object that calls callable and runnable, because Futuretask also calls the Runnable interface so it can be submitted to executor for execution.

    What is the difference between interrupted and isinterrupted methods in 8.Java?

    The main difference between interrupted () and isinterrupted () is that the former clears the interrupt state and the latter does not. The Java Multi-threading interrupt mechanism is implemented with an internal identity, and calling Thread.Interrupt () to break a thread sets the interrupt ID to true. The interrupt state is zeroed when the interrupt thread calls the static method thread.interrupted () to check the break state. The non-static method, isinterrupted (), is used to query the interrupt state of other threads without changing the interrupt status identifier. Simply put, any method that throws a Interruptedexception exception will clear the interrupt state. In any case, the interrupt state of a thread can be changed by other threads calling interrupts.

    9. If you submit a task, the thread pool queue is full. What will happen when the meeting is made?

    This question is tricky to ask, and many programmers think the task will block until the thread pool queue is empty. In fact, if a task cannot be scheduled to execute, then the Threadpoolexecutor's submit () method throws a Rejectedexecutionexception exception.

    What is the difference between the submit () and execute () methods in a 10.Java thread pool?

    Two methods can submit a task to the thread pool, the return type of the Execute () method is void, it is defined in the executor interface, and the Submit () method can return a future object holding the result of the calculation, which is defined in the Executorservice interface. It extends the executor interface, and other thread pool classes like Threadpoolexecutor and Scheduledthreadpoolexecutor have these methods.

    What is the difference between a 11.volatile variable and a atomic variable?

    First, the volatile variable and the atomic variable look alike, but the function is different. Volatile variables ensure that the antecedent relationship, that is, the write operation occurs before subsequent reads, but it does not guarantee atomicity. For example, if you modify the count variable with volatile, then the count++ operation is not atomic. The atomic method provided by the Atomicinteger class allows this operation to be atomic, such as the Getandincrement () method, which atomically increments the current value by one, and other data types and reference variables can be similarly manipulated.

    12. What happens if a thread inside a synchronization block throws an exception?

    This problem is a lot of Java programmers, if you can think of whether the lock release this clue to answer still a little hope to correct. Regardless of whether your synchronization block is normal or abnormal exit, the thread inside will release the lock, so the contrast lock interface I prefer the synchronization block, because it does not need me to expend the effort to release the lock, this function can release the lock implementation in the finally block.

    I'm the dividing line of the king of the land Tiger.

Java Pen Questions (5)

Related Article

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.