Java Interview Codex 2015 edition (definitely worth the long version of the collection)

Source: Internet
Author: User
Tags throwable

31, String s = "Hello"; s = s + "world!"; After the execution of these two lines of code, did the content in the original string object change?

No. Because string is designed as an immutable (immutable) class, all of its objects are immutable objects. In this code, s originally pointed to a string object, the content is "Hello", and then we have a + operation on S, then the object pointed to by S has changed it? The answer is no. At this point, S does not point to the original object, and point to another string object, the content is "Hello world!", the original object is still in memory, but s this reference variable no longer points to it.

With the instructions above, it is easy to derive another conclusion that if you frequently make a variety of changes to the string, or if the changes are unpredictable, then using string to represent the strings can cause significant memory overhead. Because a string object cannot be changed after it is established, a string object is required for each different string. At this point, you should consider using the StringBuffer class, which allows you to modify instead of creating a new object for each different string. Also, the conversion of these two kinds of objects is very easy.
At the same time, we can also know that if you want to use the same content string, you do not have to new a string each time. For example, we want to initialize a string reference variable named S in the constructor, set it to the initial value, and should do this:
public class Demo {
Private String S;
...
Public Demo {
s = "Initial Value";
}
...
}
Rather than
s = new String ("Initial Value");
The latter invokes the constructor every time, generates new objects, performs poorly and has a large memory overhead, and makes no sense, because the string object is immutable, so for a string of the same content, just one string object to represent it. It also says that multiple calls to the above constructor create several objects whose string type property s all point to the same object.
The above conclusion is also based on the fact that, for string constants, if the content is the same, Java considers them to represent the same string object. Calling the constructor with the keyword new always creates a new object, regardless of whether the content is the same.
As for why the string class is designed as an immutable class, it is the purpose of its decision. In fact, not only string, but many classes in the Java Standard Class library are immutable. In the development of a system, we sometimes need to design immutable classes to pass a set of related values, which is the embodiment of object-oriented thinking. Immutable classes have some advantages, such as because their objects are read-only, so there is no problem with multithreading concurrent access. Of course, there are some shortcomings, such as each different state to have an object to represent, may cause performance problems. So the Java Standard Class Library also provides a mutable version, the StringBuffer.



32. Can I inherit the String class?

The string class is the final class and cannot be inherited.



33. String s = new string ("xyz"); how many string Object did you create? What's the difference between the two?

Two or one, "xyz" corresponds to an object, which is placed in a string constant buffer, and the constant "XYZ" is the one in the buffer, no matter how many times it occurs. New string creates a new object every time it is written, and it creates a new string object with the contents of the constant "XYZ" object. If you've used ' xyz ' before, that means it won't create "xyz" yourself, just take it from the buffer.

34. The difference between string and StringBuffer

The Java platform provides two classes: string and StringBuffer, which can store and manipulate strings, which are character data that contain multiple characters. This string class provides a string of values that cannot be changed. The string provided by this StringBuffer class is modified. You can use StringBuffer when you know that character data is going to change. Typically, you can use Stringbuffers to dynamically construct character data. In addition, string implements the Equals method, new string ("ABC"). The result of equals (NewString ("abc") is true, and StringBuffer does not implement the Equals method, so the new StringBuffer ("abc"). Equals (Newstringbuffer ("abc") results in false.



Then we will give a concrete example to illustrate that we have to put together all the numbers from 1 to 100 to form a string.

StringBuffer SBF = new StringBuffer ();

for (int i=0;i<100;i++)

{

Sbf.append (i);

}

The code above is very efficient because only one StringBuffer object is created, and the following code is inefficient because 101 objects are created.

String str = new string ();

for (int i=0;i<100;i++)

{

str = str + i;

}

When talking about the difference between the two, the number of cycles should be made into 10000, and then use Endtime-begintime to compare the time difference between the two implementation, and finally to talk about the difference between StringBuilder and StringBuffer.



String overrides the Equals method and the Hashcode method, and StringBuffer does not overwrite the Equals method and the Hashcode method, so the problem occurs when the StringBuffer object is stored in the Java collection class.

35, how to convert a comma-separated string into an array?

If I don't look up the JDK API, it's hard to write! I can talk about my ideas:

1 with regular expressions, the code is probably: String [] result = Orgstr.split (",");

2 with Stingtokenizer, code: StringTokenizer tokener = StringTokenizer (Orgstr, ",");

String [] Result =new string[tokener. Counttokens ()];

Int i=0;

while (Tokener.hasnext () {Result[i++]=toker.nexttoken ();}



36. Does the array have the length () method? Does string have the length () method?

The array does not have the length () method, which has the length property. String has the length () method.

37. The following statement creates a total of how many objects: String s= "a" + "B" + "C" + "D";

Answer: For the following code:

String S1 = "a";

String s2 = s1 + "B";

String s3 = "a" + "B";

SYSTEM.OUT.PRINTLN (s2 = = "AB");

System.out.println (s3 = = "AB");

The first statement prints the result of false, the second statement prints a true result, which means that the Javac compiler can optimize the expression that adds the string constants directly, without having to wait until the run time to do the addition operation, but rather to remove the plus sign at compile time. Compiles it directly into a result that these constants are connected to.

The first line of code in the title is optimized by the compiler at compile time, which is equivalent to a string that directly defines an "ABCD", so the above code should only create a string object. Write the following two lines of code,

String s = "a" + "B" + "C" + "D";

System.out.println (s== "ABCD");

The result of the final printing should be true.

38. There is a return statement in try {}, then the code in the finally {} immediately after this try will not be executed, when executed, before or after the return?

Perhaps your answer is before return, but to be more detailed, my answer is to execute in the middle of return, see the following program code running results:

Public Classtest {



/**

* @paramargs Add by Zxx, Dec 9, 2008

*/

public static Voidmain (string[] args) {

TODO auto-generated Method Stub

System.out.println (Newtest (). Test ());;

}



static int Test ()

{

int x = 1;

Try

{

RETURNX;

}

Finally

{

++x;

}

}



}



---------Execution Results---------

1



The running result is 1, why? The main function calls the sub-function and obtains the result the procedure, like the main function prepares an empty jar, when the child function returns the result, first puts the result in the jar, then returns the program logic to the main function. The so-called return, that is, the sub-function said, I do not run, your main function to continue to run it, there is no result, the result is to say this before put into the jar.

39. What is the result of the program code output below?

public class Smallt

{

Public staticvoid Main (String args[])

{

Smallt t = new smallt ();

int b = T.get ();

System.out.println (b);

}



public int Get ()

{

Try

{

RETURN1;

}

Finally

{

return2;

}

}

}



The returned result is 2.

I can use the following example program to help me explain this answer, from the running results of the following example can be found that the return statement in the try call function is executed before the function called in Finally, that is, the return statement executed first, the finally statement after the execution, so, The returned result is 2. Return does not return the function immediately, but the return statement executes, and the returned result is placed in the function stack, and the function does not return immediately, and it does not actually begin to return until the finally statement is executed.

You can use the following procedure to help analyze the answer:

Public Classtest {



/**

* @paramargs Add by Zxx, Dec 9, 2008

*/

public static Voidmain (string[] args) {

TODO auto-generated Method Stub

System.out.println (Newtest (). Test ());;

}



int Test ()

{

Try

{

return func1 ();

}

Finally

{

return Func2 ();

}

}



int func1 ()

{

System.out.println ("func1");

return 1;

}

int Func2 ()

{

System.out.println ("Func2");

return 2;

}

}

-----------Execution Results-----------------



Func1

Func2

2



Conclusion: The code in finally executes after the return and break statements



40, final, finally, finalize the difference.

Final is used to declare properties, methods, and classes, respectively, that the property is immutable, that the method is not overridden, and that the class is not inheritable.

Internal classes to access local variables, local variables must be defined as final types, for example, a piece of code ...



Finally is part of the exception-handling statement structure, which indicates that it is always executed.





Finalize is a method of the object class that, when executed by the garbage collector, calls this method of the reclaimed object, and can override this method to provide garbage collection of other resource recycles, such as closing the file. The JVM does not guarantee that this method is always called



41. What are the similarities and differences between abnormal operation and general anomaly?

An exception represents an unhealthy state that may occur during a program's run, and a run-time exception that represents an exception that may be encountered in a typical operation of a virtual machine is a common run error. The Java compiler requires the method to declare a non-runtime exception that might occur, but does not require that a runtime exception that is not caught to be thrown must be declared.

42. What is the difference between error and exception?

Error indicates a serious problem in situations where recovery is not impossible but difficult. For example, memory overflow. It is impossible to expect the program to handle such situations. Exception represents a design or implementation issue. That is, it means that if the program runs normally, it never happens.



43. The simple principle and application of exception handling mechanism in Java.

Exceptions are abnormal conditions or errors that occur when a Java program is run (not compiled), similar to real-life events, where real-life events can contain information about the time, place, people, and plot of an event, which can be represented by an object, and Java uses an object-oriented approach to handling exceptions. It encapsulates each exception that occurs in the program into an object that contains information about the exception.

Java classifies exceptions, and different types of exceptions are represented by different Java classes. The root class for all exceptions is java.lang.throwable,throwable and derives two sub-classes: Error and Exception,error represent a serious problem that the application itself cannot overcome and recover, and the program is only dead, for example, system problems such as memory overflow and thread deadlock. Exception said that the program can also overcome and restore the problem, which is divided into system anomalies and common anomalies, system anomalies are the defects of the software itself caused by problems, that is, the software developers to consider the problem caused by poor, software users can not overcome and restore this problem, In this case, however, the software system can continue to run or let the software die, for example, array scripting out of bounds (arrayindexoutofboundsexception), null pointer exception (NULLPOINTEREXCEPTION), Class Conversion Exception (classcastexception), common exception is the operation of the environment changes or anomalies caused by the problem, is the user can overcome the problem, for example, network disconnection, hard disk space is not enough, after such an exception, the program should not die.

Java provides a different solution for system exceptions and common exceptions, and the compiler enforces common exceptions that must try: Catch processing or using the throws declaration continues to be thrown to the upper call method processing, so the common exception is also called the checked exception, and the system exception can be handled or not handled, so the compiler does not enforce with try. catch processing or declaration with throws, so system exceptions are also known as unchecked exceptions.



Prompt answer: According to three levels to think: the virtual machine must be down the error, the program can die or can not die of errors, the program should not die error;

44. Please write down the 5 runtime exception you are most familiar with.

This question mainly test your code amount is how big, if you long-term write code, should often see some system aspects of anomalies, you do not have to answer 5 specific system exceptions, but you have to be able to say what is the system anomaly, and a few system exceptions can be, of course, These exceptions are completely written in their English name is the best, if it is not written, then use Chinese bar, there is better than no strong!

The so-called system anomaly, that is ..., they are runtimeexception subclasses, in the JDK doc in the RuntimeException class, you can see all its subclasses list, that is to see all the system exceptions. I am more impressed with the system anomalies are: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.

45, the Java language How to handle exception, keyword: throws,throw,try,catch,finally what is the meaning of each? Can I throw an exception in a try block?

46. There are several ways to implement a thread in Java? What keyword modifies the synchronization method? Why is the Stop () and suspend () methods not recommended?



Java5 before, as in the following two kinds:

The first type:

New Thread () {}.start (); This means that the run method of the thread subclass object is called, and new Thread () {} represents an instance object of an anonymous subclass of thread, with the following code for the subclass plus the Run method:

New Thread () {

public void Run () {

}

}.start ();



The second type:

New Thread (New Runnable () {}). Start (); This means that the run method of the Runnable object accepted by the Thread object is called, and new Runnable () {} represents an instance object of an anonymous subclass of Runnable. The code for the Runnable subclass plus the Run method is as follows:

New Thread (New Runnable () {

Public Voidrun () {

}

}

). Start ();





Starting with Java5, there are a number of thread pools that create multithreading:

Executorservice pool = Executors.newfixedthreadpool (3)

for (int i=0;i<10;i++)

{

Pool.execute (Newrunable () {public void Run () {}});

}

Executors.newcachedthreadpool (). Execute (new runable () {publicvoid run () {}});

Executors.newsinglethreadexecutor (). Execute (new runable () {publicvoid run () {}});







There are two implementations, using the form new thread () and new Thread (runnable), the first to directly invoke the thread's Run method, so we tend to use the thread subclass, New Subthread (). The second call to Runnable's Run method.



There are two implementation methods, namely, inheriting the thread class and implementing the Runnable interface.

Using the Synchronized keyword to modify the synchronization method

Against the use of Stop () is because it is unsafe. It unlocks all locks acquired by the thread, and if the object is in an incoherent state, then other threads can examine and modify them in that state. The result is hard to check out the real problem. The suspend () method is prone to deadlocks. When calling suspend (), the target line routines stops, but still holds the lock that was acquired before. At this point, no other thread can access the locked resource unless the thread that is "suspended" resumes running. For any thread, if they want to restore the target thread while trying to use any of the locked resources, it will cause a deadlock. So instead of using suspend (), you should place a flag in your own thread class that indicates whether the thread should be active or suspended. If the flag indicates that the thread should hang, use wait () to enter the wait state. If the flag indicates that the thread should be resumed, restart the thread with a notify ().

47. What is the difference between sleep () and wait ()?

(Online answer: Sleep is a thread-class method that causes this thread to pause execution for a specified time, giving the execution opportunity to other threads, but the monitoring State remains, and is automatically restored after that time.) Calling sleep does not release the object lock. Wait is a method of the object class that calls the wait method on this object to cause this thread to discard the object lock, enter the waiting lock pool waiting for this object, and only after the Notify method (or Notifyall) is issued for this object the thread enters the object lock pool ready to get the object lock into the running state. )



Sleep is the thread that is executing the active cpu,cpu to execute other threads, the CPU will go back to this thread after the time specified by sleep, and if the current thread enters a sync lock, the Sleep method does not release the lock. Even if the current thread uses the Sleep method to give out the CPU, other threads that are blocked by the sync lock cannot be executed. Wait refers to a thread that has entered a sync lock, allowing itself to temporarily let out a sync lock so that other threads waiting for the lock can get a synchronous lock and run, and only other threads call the Notify method (notify does not release the lock, Just tell the thread that called the wait method to be able to participate in the competition to get the lock, but not immediately get the lock, because the lock is still in the hands of others, others have not been released. If the code behind the Notify method is much more, it needs to be executed before releasing the lock, you can add a wait and some code after the Notfiy method, see the effect), the thread that calls the wait method will dismiss the wait state and the program can continue to run down after the lock is received again. Wait for the explanation must be in line with the example code to illustrate, only to appear that they really understand.

Package Com.huawei.interview;



Publicclass multithread {



/**

* @paramargs

*/

public static Voidmain (string[] args) {

TODO auto-generated Method Stub

New Thread (NewThread1 ()). Start ();

try {

Thread.Sleep (10);

} catch (Interruptedexception e) {

TODO auto-generated Catchblock

E.printstacktrace ();

}

New Thread (NewThread2 ()). Start ();

}





private static Classthread1implements Runnable

{



@Override

public void Run () {

TODO auto-generated methodstub

Since the Thread1 and the following Thread2 internal run methods use the same object as the monitor, we cannot use this here because the this in Thread2 and this Thread1 is not the same object. We use Multithread.class, the byte-code object, which refers to the same object when the variable is referenced in the current virtual machine.

Synchronized (Multithread.class) {



System.out.println ("Enterthread1 ...");



System.out.println ("Thread1is Waiting");

try {

There are two ways to release a lock, the first being that the program naturally leaves the range of the monitor, that is, the code range that leaves the Synchronized keyword, and the wait method for the monitor object within the code that the Synchronized keyword governs. Here, use the Wait method to release the lock.

MultiThread.class.wait ();

} catch (Interruptedexception e) {

TODO Auto-generatedcatch Block

E.printstacktrace ();

}



System.out.println ("Thread1is going on ...");

System.out.println ("Thread1is being over!");

}

}



}



private static Classthread2implements Runnable

{



@Override

public void Run () {

TODO auto-generated methodstub

Synchronized (Multithread.class) {



System.out.println ("Enterthread2 ...");



System.out.println ("thread2notify other thread can release wait status.");

Because the Notify method does not release the lock, even though Thread2 calls the sleep method below for 10 milliseconds, Thread1 still does not execute because THREAD2 does not release the lock, so Thread1 cannot get the lock.



MultiThread.class.notify ();



System.out.println ("Thread2is sleeping ten Millisecond ...");

try {

Thread.Sleep (10);

} catch (Interruptedexceptione) {

TODO Auto-generatedcatch Block

E.printstacktrace ();

}



System.out.println ("Thread2is going on ...");

System.out.println ("Thread2is being over!");



}

}



}



}





48. What are the similarities and differences between synchronous and asynchronous, and under what circumstances are they used separately? An example is described.

If the data will be shared between threads. For example, the data being written may be read by another thread later, or the data being read may have been written by another thread, then the data is shared and must be accessed synchronously.

When an application calls a method that takes a long time to execute on an object and does not want the program to wait for the method to be returned, it should use asynchronous programming, which is often more efficient in many cases with asynchronous approaches.



49. Are the following two methods synchronized? (Invented by himself)

Class Test

{

Synchronizedstatic VoidsayHello3 ()

{



}



Synchronizedvoid GetX () {}

}

50, multithreading there are several ways to achieve? How many ways to implement synchronization?

There are two ways to implement multithreading, namely, inheriting the thread class and implementing the Runnable interface.

There are two implementations of synchronization, namely Synchronized,wait and notify

Wait (): causes a thread to be in a wait state and releases the lock of the object it holds.

Sleep (): Makes a running thread sleep, is a static method that calls this method to catch the interruptedexception exception.

Notify (): Wakes up a waiting thread, noting that when this method is called, it does not actually wake up a waiting state thread, but is determined by the JVM to wake up which thread, and not by priority.

Allnotity (): Wakes all the threads that are in the waiting state, noting that they do not give all the wake-up threads an object lock, but instead let them compete.

Java Interview Codex 2015 edition (definitely worth the long version of the collection)

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.