This is one of the most useful Java interview questions I've ever seen, interviewing countless companies summarizing

Source: Internet
Author: User
Tags int size stub switch case thread class

"Declaration" Source: Power node Java Institute, reprint Source: Script House

(The answer to a small number of questions was slightly altered by me)

1, what is the thread local variable.

A thread-local variable is a variable within the thread itself, owned by the thread itself, and not shared among multiple threads. Java provides a ThreadLocal class to support thread-local variables, which is a way to achieve thread safety. However, in a management environment, such as a Web server, use a thread-local variable with special care, in which case the worker thread's life cycle is longer than any application variable. Once any thread local variable has not been released after the work has been completed, the Java application is at risk of memory leaks.


2. Write a piece of code with wait-notify to solve the producer-consumer problem.

Please refer to the sample code in the answer. Just remember to call the Wait () and notify () method in the synchronization block, and if blocking, test the waiting condition by looping.

Producers

Package com.edu.chapter03.test;  
Import Java.util.Vector;  
Import Java.util.logging.Level;  
  
Import Java.util.logging.Logger;  
    public class Producer implements Runnable {private final Vector sharedqueue;  
      
    private final int SIZE;  
        Public Producer (Vector sharedqueue, int size) {this.sharedqueue = Sharedqueue; This.  
    size = size;  @Override public void Run () {//TODO auto-generated a stub for (int i = 0; i < 7;  
            i++) {System.out.println ("produced:" + i);  
            try {produce (i); The catch (Interruptedexception ex) {Logger.getlogger (Producer.class.getName ()). log (Level.severe, NULL, E  
            x); }} private void produce (int i) throws interruptedexception {//wait if Qu Eue is full while (sharedqueue.size () = size) {synchronized (sharedqueue{System.out.println ("Queue is full" + thread.currentthread ()). GetName () + "  
                Is waiting, size: "+ sharedqueue.size ());  
            Sharedqueue.wait ();  
            }//producing element and notify consumers synchronized (Sharedqueue) {  
            Sharedqueue.add (i);  
        Sharedqueue.notifyall ();   }  
    }  
}

Consumer

Package com.edu.chapter03.test;  
Import Java.util.Vector;  
Import Java.util.logging.Level;  
  
Import Java.util.logging.Logger;  
    public class Consumer implements Runnable {private final Vector sharedqueue;  
      
    private final int SIZE;  
        Public Consumer (Vector sharedqueue, int size) {this.sharedqueue = Sharedqueue; This.  
    size = size;  
            @Override public void Run () {//TODO auto-generated Method Stub (True) {  
                try {System.out.println ("Consumer:" + consume ());  
            Thread.Sleep (50); The catch (Interruptedexception ex) {Logger.getlogger (Consumer.class.getName ()). log (Level.severe, NULL, E  
            x); '}} private int consume () throws Interruptedexception {//wait if Queu  
  E is empty while (Sharedqueue.isempty ()) {synchronized (sharedqueue) {              System.out.println ("Queue is empty" + thread.currentthread (). GetName () + ' is Wai  
                Ting, size: "+ sharedqueue.size ());  
            Sharedqueue.wait (); }//otherwise consume element and notify waiting producer synchronized (SHAREDQ  
            Ueue) {sharedqueue.notifyall ();  
        Return (Integer) sharedqueue.remove (0);   }  
    }  
}

"Test Function"

Package com.edu.chapter03.test;  
Import Java.util.Vector;  
  
public class Producerconsumersolution {public  
  
    static void Main (string[] args) {  
        vector sharedqueue = new Vector () ;  
        int size = 4;  
        Thread prodthread = new Thread (new Producer (sharedqueue, size), "Producer");  
        Thread consthread = new Thread (new Consumer (sharedqueue, size), "Consumer");  
        Prodthread.start ();  
        Consthread.start ();  
    }  

3. Write a thread-safe single case pattern (Singleton) in Java.


Please refer to the sample code in the answer, which teaches you to create a thread-safe Java Single Instance class step-by-step. When we say thread safety, it means that even if initialization is in a multithreaded environment, a single instance can still be guaranteed. In Java, using enumerations as a single instance class is the easiest way to create a thread-safe single case pattern.


Load now/A hungry man type:

"The instance is already created before the method is invoked."

Package com.weishiyao.learn.day8.singleton.ep1;

public class MyObject {
  //immediate load mode = = Evil Han mode
  private static MyObject MyObject = new MyObject ()

  ; Private MyObject () {
  } public
  
  static MyObject getinstance () {
    //This code version for immediate loading
    ////This version of the code has the disadvantage that there cannot be other instance variables
    Because the getinstance () method is not synchronized
    //So it is possible to have a thread-safe problem return
    MyObject
  }
}

"Create a Thread class"

Package com.weishiyao.learn.day8.singleton.ep1;

public class Mythread extends Thread {
  @Override public
  void Run () {
    System.out.println ( Myobject.getinstance (). Hashcode ());
  }
"Create Run Class"
Package com.weishiyao.learn.day8.singleton.ep1;

public class Run {public
  static void Main (string[] args) {
    mythread t1 = new Mythread ();
    Mythread t2 = new Mythread ();
    mythread t3 = new Mythread ();
    T1.start ();
    T2.start ();
    T3.start ();
  }

Lazy load/lazy type

"Building an instance of an object"

Package COM.WEISHIYAO.LEARN.DAY8.SINGLETON.EP2;

public class MyObject {
  private static MyObject MyObject;
  
  Private MyObject () {
    
  } public
  
  static MyObject getinstance () {
    //deferred load
    if (MyObject!= null) {
      
    } else {
      myObject = new MyObject ();
    }
    Return MyObject
  }
}

"Create a Thread class"

Package COM.WEISHIYAO.LEARN.DAY8.SINGLETON.EP2;

public class Mythread extends Thread {
  @Override public
  void Run () {
    System.out.println ( Myobject.getinstance (). Hashcode ());
  }

"Create Run Class"

Package COM.WEISHIYAO.LEARN.DAY8.SINGLETON.EP2;

public class Run {public
  static void Main (string[] args) {
    mythread t1 = new Mythread ();
    T1.start ();
  }

"Run Test Class"

Package COM.WEISHIYAO.LEARN.DAY8.SINGLETON.EP2;

public class Run {public
  static void Main (string[] args) {
    mythread t1 = new Mythread ();
    Mythread t2 = new Mythread ();
    mythread t3 = new Mythread ();
    mythread T4 = new Mythread ();
    Mythread T5 = new Mythread ();
    T1.start ();
    T2.start ();
    T3.start ();
    T4.start ();
    T5.start ();
  }

The difference between the sleep method in 4.Java and the Wait method.


Although both are used to pause the currently running thread, but sleep () is actually just a short pause because it does not release the lock, and wait () means the condition waits, which is why the method releases the lock because only then can other waiting threads acquire the lock when the condition is met.


5. What is immutable (immutable object). How to create a immutable object in Java.


Immutable objects mean that once an object is created, the state cannot be changed. Any modification creates a new object, such as String, Integer, and other wrapper classes. See answers for details, step-by-step instructions to create immutable classes in Java.


6. Can we create an immutable object that contains a mutable object?


Yes, we can create an immutable object that contains a Mutable object, you just need to be careful not to share a mutable object's reference, and if you need to change, return a copy of the original object. The most common example is a reference to an object that contains a Date object.


What data types should be used in 7.Java to represent prices.


If you are not particularly concerned with memory and performance, use BigDecimal, otherwise use the predefined precision double type.


8. How to convert byte to String.


You can use String to receive the byte[] parameter's constructor for conversion, the point to be aware of is to use the correct encoding, otherwise you will use the platform default encoding, this encoding may be the same as the original encoding, may also be different.


The conversion of bytes and other types in 9.Java.


public class Test {private static Bytebuffer buffer = Bytebuffer.allocate (8);    
        public static void Main (string[] args) {//test int turn byte int int0 = 234;    
        byte Byte0 = Inttobyte (int0);    
        System.out.println ("byte0=" + byte0);//byte0=-22//test byte to int int int1 = Bytetoint (BYTE0);    
        System.out.println ("int1=" + int1);//int1=234//test int to byte array int int2 = 1417;    
        byte[] Bytesint = Inttobytearray (Int2); System.out.println ("bytesint=" + bytesint);//bytesint=[b@de6ced//test byte array int int int3 = Bytea    
        Rraytoint (Bytesint); System.out.println ("int3=" + int3);//int3=1417//test long-byte array lon    
        G long1 = 2223;    
        byte[] Byteslong = longtobytes (long1); System.out.println ("bytes=" + byteslong);//bytes=[b@c17164//test byte array to long long long2 = Bytestolong (Byteslong); System.out.println ("long2=" + long2);//long2=2223}//byte and int convert to public    
    static byte inttobyte (int x) {return (byte) x;    
        The public static int bytetoint (byte b) {//java always treats byte as a character; we can make it binary with 0xFF and get its No value    
    return B & 0xFF; Conversion of//byte array to int public static int bytearraytoint (byte[] b) {return b[3] &A mp    
                0xFF |    
                (B[2] & 0xFF) << 8 |    
                (B[1] & 0xFF) << 16 |    
    (B[0] & 0xFF) << 24; public static byte[] Inttobytearray (int a) {return new byte[] {(byte) (a &G T;> & 0xFF), (Byte) ((a >>) & 0xFF), (Byte) ((a >> 8) &am P       
           0xFF), (byte)    
    (A & 0xFF)};    
        The//byte array and long convert to each other public static byte[] Longtobytes (long x) {Buffer.putlong (0, X);    
    return Buffer.array ();    
        public static long Bytestolong (byte[] bytes) {buffer.put (bytes, 0, bytes.length);    
    Buffer.flip ();//need Flip return Buffer.getlong (); }    
}


10. Can we cast int to a variable of type byte? What happens if the value is greater than the byte type's range.


Yes, we can do a cast, but in Java the int is 32 bits, and byte is 8 bit, so if the force conversion is, the high 24 bits of the int type will be discarded and the byte type range from-128 to 128.


11. There are two classes, B inherits A,c inheritance B, can we convert B to C. such as C = (c) B;


Can, downward transition. However, it is not recommended to use, prone to type transition anomalies.


12. Which class contains the Clone method. is cloneable or Object.


Java.lang.Cloneable is an indicative interface that does not contain any methods, and the Clone method is defined in the object class. And you need to know that the Clone () method is a local method, which means that it is implemented in C or C + + or other local languages.


The 13.Java + + operator is thread-safe.


is not a thread-safe operation. It involves multiple instructions, such as reading a variable value, adding it, and then storing it back into memory, a process that may occur with multiple threads.


14.a = The difference between A + B and a = b


+ + implicitly casts the result type of the operation to the type holding the result. If the two integers are added, such as Byte, short, or int, they are first elevated to the int type, and then the addition operation is performed. If the result of an addition operation is larger than the maximum value of a, then A+b will have a compile error, but A + B is fine, as follows:


byte a = 127;

byte B = 127;

b = A + B; Error:cannot convert from int to byte

B + A; Ok


(Translator Note: This place should be expressed in error, in fact, regardless of the value of A+b, the compiler will complain, because the a+b operation will be a, b promoted to int type, so the int type assignment to byte will compile error)


15. Can I assign a double value to a long variable without a cast?


No, you can't. Assign a double value to a long variable without coercion of type conversions, because the double type has a wider range than long, so you must cast it.


16.3*0.1 = 0.3 will return what. True or FALSE.


False, because some floating-point numbers cannot be expressed exactly.


17.int and Integer which will consume more memory.


An Integer object consumes more memory. An Integer is an object that requires the storage of the object's metadata. But int is a raw type of data, so it takes less space.


18. Why String in Java is immutable (immutable).


String immutable in Java is because the designer of Java thinks that strings are used very frequently, and setting the string to immutable can allow multiple clients to share the same string. See answers for more details.


19. Can we use String in Switch?


Starting with Java 7, we can use strings in switch case, but this is just a syntactic candy. The internal implementation uses the hash code of the string in the switch.


What is the constructor chain in 20.Java.


When you invoke another constructor from a constructor, it is the constructor chain in Java. This situation only occurs when the constructor of the class is overloaded.


In a 21.64-bit JVM, the length of an int is the majority.


In Java, the length of an int type variable is a fixed value, regardless of the platform, and is 32 bits. This means that in 32-bit and 64-bit Java virtual machines, the length of the int type is the same.


The difference between 22.Serial and Parallel GC.

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.