Java face question (ii)

Source: Internet
Author: User
Tags throwable wrapper

The system has organized a bit of questions about Java, including Basic, Javaweb, frame, database, multi-threaded, concurrent articles, algorithms and so on, updated in succession. Other aspects such as the front end and so on the face of the questions are also in the collation, there will be.

Note: At the end of the article there are benefits!

1. String s = new string ("xyz"); how many stringobject have been created? Can I inherit the String class?

Two or one is possible, "XYZ" corresponds to an object, the object is placed in a string constant buffer, and the constant "XYZ" is the one in the buffer, no matter how many times it occurs. NewString creates a new object every time it is written, it creates a new string object using the contents of the constant "XYZ" object. If ' xyz ' had been used before, then "XYZ" would not have been created and would have been taken directly from the buffer, when a stringobject was created, but if "XYZ" had not been used before, then an object was created and put into the buffer, in which case it created two objects. As to whether the string class inherits, the answer is no, because the string default final decoration is not inheritable.

2. 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 can be 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.

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

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 compilation can be optimized for the expression that adds the string constants directly, without having to wait until the run time to do the addition processing, but 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.

4, try {} has a return statement, then immediately after this try finally{} code will not be executed, when executed, before return or after?

We know that the statement in the finally{} is bound to execute, then this may be normal to blurt out before return, after return may be out of this method, the ghost knows where to go, but more accurate should be in return in the middle of execution, see the following program code running results:

Public classtest {public    static void Main (string[]args) {       System.out.println (newtest (). Test ());;    }    static int test ()    {       intx = 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.

5, 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.

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. However, the JVM does not guarantee that this method is always called

6. 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.

7 , 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.

8. Simply talk about 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, different types of exceptions are represented by different Java classes, and the root class for all exceptions is java.lang.throwable,throwable with two sub-classes derived below:

Error and Exception,error represent a serious problem that the application itself cannot overcome and recover, and the program only crashes, for example, a system problem such as memory overflow and thread deadlock.

Exception indicates that the program can also overcome and recover problems, which are divided into system exceptions and common exceptions:

System anomaly is the problem caused by the defects of software itself, which is caused by the poor consideration of software developers, and software users cannot overcome and recover the problem, but in this case the software system can continue to run or let the software hang out, for example, Array script out of bounds (arrayindexoutofboundsexception), null pointer exception (NULLPOINTEREXCEPTION), class conversion exception (classcastexception);

Ordinary exception is the operating environment changes or anomalies caused by the problem, is the user can overcome problems, such as 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.

9. What is the difference between heap and stack in Java?
The heap and stack in the JVM belong to different memory regions and are used for different purposes. Stacks are often used to save method frames and local variables, and objects are always allocated on the heap. Stacks are usually smaller than heaps and are not shared across multiple threads, and the heap is shared by all threads of the entire JVM.

Stacks: Some of the basic types of variables defined in the function and the reference variables of the objects are allocated in the stack memory of the function, and when a variable is defined in a block of code, Java allocates the memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated for that variable. The memory space can be used immediately by another.

Heap: Heap memory is used to store the objects and arrays created by new, and the memory allocated in the heap is managed by the automatic garbage collector of the Java virtual machine. After creating an array or an object in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object. The reference variable in the stack can then be used in the program to access an array or an object in the heap, which is equivalent to a name that is an array or an object.

10. can i cast int to a variable of type byte? What happens if the value is greater than the range of type byte?
We can do the cast, but the int in Java is 32 bits, and byte is 8 bits, so if you force conversions, the high 24 bits of the int type will be discarded because the byte type range is from-128 to 127.

1 1. What is the use of A.hashcode ()? What is the relationship with A.equals (b)?
The Hashcode () method corresponds to the hash value of the integer type of the object. It is often used for hash-based collection classes such as Hashtable, HashMap, Linkedhashmap, and so on. It is particularly closely related to the Equals () method. According to the Java specification, two objects that use the equal () method to determine equality must have the same hash code.

1 2, the difference between the character stream and the byte stream

To output a piece of binary data to a device one at a time, or to read a piece of binary data from one device at a time, no matter what the input is, we need to do it in a uniform way, describing it in an abstract way, which is named IO Stream, The corresponding abstract classes are OutputStream and inputstream, and different implementation classes represent different input and output devices, all of which operate on bytes.

Everything in the computer ends up being binary bytes. For frequently used Chinese characters, the corresponding byte is first obtained, and then the bytes are written to the output stream. Read, the first read is the byte, but we want to display it as a character, we need to convert the bytes into characters. Because of this wide range of requirements, Java specifically provides a character stream wrapper class.

The underlying device always accepts only byte data, and sometimes writes a string to the underlying device, which needs to be converted to bytes and then written. The character stream is the wrapper of the byte stream, and the character stream is directly accepting the string, which internally turns the strings into bytes and writes to the underlying device, which provides a little bit of convenience for us to write or read the string to the IO device.

When converting a character to a byte, pay attention to the problem of encoding, because the string into a byte array, in fact, is converted to the character of some kind of encoded byte form, reading is the other way around.

1 3. What is Java serialization and how do I implement Java serialization? Or, explain the role of the serializable interface.

There are times when we turn a Java object into a byte stream or revert from a byte stream to a Java object, for example, to store Java objects on a hard disk or to send to other computers on the network. In this process, we can write our own code to transform a Java object into a stream of bytes in a format.

However, the JRE itself provides this support, we can call OutputStream's WriteObject method to do, if we want to let Java help us do, the object to be transferred must implement the Serializable interface, so that Javac compile time will be special processing , the compiled class can be manipulated by the WriteObject method, which is called serialization. The class that needs to be serialized must implement the Serializable interface, which is a mini interface, where there is no need to implement a method, implements serializable just to annotate that the object is serializable.

For example, in web development, if the object is stored in the session and Tomcat is restarting to serialize the session object to the hard disk, the object must implement the Serializable interface. If an object is to be transmitted over a distributed system, the transmitted object must implement the Serializable interface.

1 4. Describe the principle mechanism of the JVM loading class file?

The loading of classes in the JVM is implemented by ClassLoader and its subclasses, and Java ClassLoader is an important Java Runtime system component. It is responsible for locating and loading classes of class files at run time.

1 5. What is the difference between heap and stack?

Java's memory is divided into two categories, one is stack memory, and the other is heap memory. Stack memory is when a program enters a method, it allocates a private storage space for the method, which stores the local variables inside the method, and when the method ends, the stack allocated to the method is freed, and the variables in the stack are freed.

A heap is a memory that is different from the stack and is typically used to hold data that is not in the current method stack, for example, objects created with new are placed in the heap, so it does not disappear with the end of the method. The local variables in the method are placed in the heap instead of the stack, using the final decoration.

1 6. What is GC? Why do you have a GC?

GC is the meaning of garbage collection (Gabage Collection), memory processing is where programmers are prone to problems, forgetting or wrong memory recycling can cause program or system instability or even crashes, The GC functionality provided by Java can automatically monitor whether an object exceeds the scope to achieve the purpose of automatically reclaiming memory, and the Java language does not provide a way to release the displayed operation of the allocated memory.

1 7, the advantages and principles of garbage collection. and consider 2 kinds of recycling mechanisms.

A notable feature of the Java language is the introduction of a garbage collection mechanism, which makes it possible for the C + + programmer to solve the most troublesome memory management problems, which makes it unnecessary for Java programmers to consider memory management when writing programs. Because of the garbage collection mechanism, objects in Java no longer have a "scope" concept, and only references to objects have a scope.

Garbage collection can effectively prevent memory leaks and effectively use memory that can be used. The garbage collector is usually run as a separate low-level thread, and in unpredictable cases the dead or unused objects in the heap are purged and reclaimed, and the programmer cannot call the garbage collector in real time to garbage collection of an object or all objects.

The recycling mechanism has generational replication garbage collection and token garbage collection, incremental garbage collection.

1 8. What is the basic principle of the garbage collector? Can the garbage collector reclaim memory right away? Is there any way to proactively notify a virtual machine for garbage collection?

For GC, when a programmer creates an object, the GC starts to monitor the object's address, size, and usage. Typically, a GC uses a graph to record and manage all objects in the heap. In this way, you determine which objects are "accessible" and which objects are "unreachable." When the GC determines that some objects are unreachable, it is the responsibility of the GC to reclaim those memory spaces.

The programmer can manually execute System.GC () to notify the GC to run, but the Java language specification does not guarantee that the GC will execute.

1 9. What is the difference between throw and throws in Java?

Throw is used to throw an instantiated object of the Java.lang.Throwable class, meaning that you can throw a exception through the keyword throw, such as:
throw new IllegalArgumentException ("Xxxxxxxxx″")

The function of throws is as part of the method declaration and signature, and the method is thrown with the appropriate exception so that the caller can handle it. In Java, any unhandled checked exception is forced to be declared in the throws clause.

2 is there a memory leak in the 0,java, please describe it briefly.

Explain what a memory leak is: the so-called memory leak refers to an object or variable that is not being used by the program has been occupied in memory. There is a garbage collection mechanism in Java that ensures that objects are automatically erased from memory by the garbage collector when the object is no longer referenced.

Because Java uses a graph-like approach to garbage collection management, you can eliminate the problem of reference loops, such as having two objects and referencing each other, so that GC can reclaim them as long as they and the root process are unreachable.

Memory leaks in Java: Long life-cycle objects that hold references to short life-cycle objects are likely to have a memory leak, even though short life-cycle objects are no longer needed, but because long-life-cycle objects hold their references and cannot be recycled, this is where memory leaks occur in Java, in layman's words, Is that the programmer might have created an object that would never be used in the future, and this object has been referenced, that is, the object is useless but cannot be reclaimed by the garbage collector, which is a possible memory leak in Java, for example, the cache system, we loaded an object in the cache ( For example, in a global map object), and then no longer using it, the object has been cached for reference, but is no longer used.

Follow the public number reply to the Java question to get the PDF version!

A conscience public number "IT resources":

This public number is committed to free sharing of the best video resources, learning materials, interview experience, Front end, Php,java, algorithms, Python, big Data and so on, which you want to have

IT Resources-QQ Exchange Group: 625494093

Can also add pull you into the group: super1319164238

Search public Number: Itziyuanshe or scan the QR code below direct attention,

Java face question (ii)

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.