JAVA interview Selection [Java basics Part 3]

Source: Internet
Author: User

In the previous article, we gave about 35 questions, all of which are basic knowledge. Some children's shoes reflect that the questions are outdated. In fact, they are not. These are the foundation of the basics, but they are also essential, there are still some basic questions in the interview questions. We gradually give different levels of questions based on the principle of ease and difficulty. Continue with the 70 questions mentioned last time. This chapter will provide 13 typical questions for kids shoes

  71. Give up to five common classes, packages, and interfaces.

To make people feel familiar with java ee development, you should not just list those items in core java, but also list the items involved in your ssh project. Write the classes involved in the programs you recently wrote.

 

Common classes: BufferedReader BufferedWriter FileReader FileWirter String Integer

Java. util. Date, System, Class, List, HashMap

 

Common packages: java. lang java. io java. util java. SQL, javax. servlet, org. apache. strtuts. action, org. hibernate

Common interfaces: Remote List Map Document NodeList, Servlet, HttpServletRequest, HttpServletResponse, Transaction (Hibernate), Session (Hibernate), HttpSession

72. How many types of streams are there in java? JDK provides some abstract classes for each type of stream for inheritance. which classes are they?

Byte stream: bytes stream. Byte streams are inherited from InputStream OutputStream, and bytes streams are inherited from InputStreamReaderOutputStreamWriter. There are many other streams in the java. io package, mainly to improve performance and ease of use.

73. Differences between byte streams and byte streams

To output one piece of binary data to a device one by one, or read one piece of binary data from a device one by one, no matter what the input/output device is, we need to perform these operations in a unified manner and describe them in an abstract way. This abstract description method is named IO stream, and the corresponding abstract classes are OutputStream and InputStream, different implementation classes represent different input and output devices. They all operate on bytes.

In applications, it is often necessary to output or read a piece of text with full characters. Can I use Word throttling? Everything in the computer eventually exists in a binary byte format. For the "China" character, first obtain the corresponding byte and then write the byte to the output stream. When reading, the first thing we read is the byte. But to display it as a character, we need to convert the byte into a character. Due to this wide range of needs, people have specialized in providing the packaging class of the volume stream.

The underlying device always only accepts byte data. Sometimes, to write a string to the underlying device, you need to convert the string into bytes before writing it.Byte stream is the packaging of byte streams.,The accept stream directly accepts strings.It internally converts the string into bytes and then writes it to the underlying device, which makes it a little easier for us to write or read strings to IO settings.

Attention should be paid to encoding when converting characters to bytes.Because the string is converted into a byte array,

It is actually a byte form converted into a certain encoding of the character, and reading is also the opposite principle.

 

Code example of the relationship between byte stream and byte stream:

Import java. io. BufferedReader;

Import java. io. FileInputStream;

Import java. io. FileOutputStream;

Import java. io. FileReader;

Import java. io. FileWriter;

Import java. io. InputStreamReader;

Import java. io. PrintWriter;

 

Public class IOTest {

Public static void main (String [] args) throws Exception {

String str = "Chinese ";

/* FileOutputStreamfos = newFileOutputStream ("1.txt ");

 

Fos. write (str. getBytes ("UTF-8 "));

Fos. close ();*/

 

/* FileWriter fw = new FileWriter ("1.txt ");

Fw. write (str );

Fw. close ();*/

PrintWriter pw = new PrintWriter ("1.txt"," UTF-8 ");

Pw. write (str );

Pw. close ();

 

/* FileReader fr = new FileReader ("1.txt ");

Char [] buf = newchar [1024];

Int len = fr. read (buf );

String myStr = newString (buf, 0, len );

System. out. println (myStr );*/

/* FileInputStreamfr = new FileInputStream ("1.txt ");

Byte [] buf = newbyte [1, 1024];

Int len = fr. read (buf );

String myStr = newString (buf, 0, len, "UTF-8 ");

System. out. println (myStr );*/

BufferedReader br = new BufferedReader (

NewInputStreamReader (

NewFileInputStream ("1.txt")," UTF-8"

)

);

String myStr = br. readLine ();

Br. close ();

System. out. println (myStr );

}

 

}

74. What is java serialization and how to implement java serialization? Alternatively, explain the functions of the Serializable interface.

 

We sometimes convert a java object into a byte stream or restore it to a java object from a byte stream. For example, to store java objects to hard disks or to other computers on the network, we can write code to convert a java object into a byte stream of a certain format before transmission. However, jre itself provides this support. We can call the writeObject method of OutputStream to do this. If we want java to help us,The object to be transmitted must implement the serializable interface.In this way, special processing will be performed during javac compilation, and the compiled class can be operated by the writeObject method. This is called serialization. The class to be serialized must implement the Serializable interface, which is a mini interface, with no implementation method in it, implementsSerializableOnly to mark that the object is serializable.

 

 

For example, in web development, if an object is stored in a Session, tomcat will serialize the Session object to the hard disk during restart, and the object must implement the Serializable interface. If the object needs to be transmitted through the distributed system or remotely called through rmi, the object needs to be transmitted over the network. The transmitted object must implement the Serializable interface.

 

75. How does JVM load class files?

In JVM, class loading is implemented by ClassLoader and its subclass. Java ClassLoader is an important Java runtime system component. It is responsible for finding and loading classes of class files at runtime.

 

76. What is the difference between heap and stack.

Java memory is divided into two types: stack memory and stack memory. Stack memory refers to a private bucket allocated separately for the method when the program enters a method. It is used to store local variables in the method. When the method ends, the stack assigned to this method will be released, and the variables in this stack will also be released.

The heap memory is different from the stack memory. It is generally used to store data that is not stored in the current method stack. For example, all objects created using new are stored in the heap. Therefore, it does not disappear with the end of the method.The local variables in the method are modified using final and placed in the heap instead of the stack.

 

77. What is GC? Why does GC exist?

GC is the meaning of garbage Collection (Gabage Collection). Memory Processing is a place where programmers are prone to problems. Forgetting or wrong memory Collection can lead to instability or even crash of programs or systems, the GC function provided by Java can automatically monitor whether the object has exceeded the scope to achieveAutomatic memory recoveryJava language does not provide a display operation method to release allocated memory.

 

78. Advantages and principles of garbage collection. Two recovery mechanisms are also considered.

A notable feature of Java is the introduction of the garbage collection mechanism, which helps c ++ programmers solve the most troublesome memory management problems, it makes memory management unnecessary for Java programmers when writing programs. Because of the garbage collection mechanism, objects in Java do not have the "Scope" concept, and only objects can be referenced with "Scope ". Garbage collection can effectively prevent memory leakage and effectively use available memory. The garbage collector is usually used as a separate low-level thread to clear and recycle objects that have been killed in the memory heap or are not used for a long time, programmers cannot call the Garbage Collector to recycle an object or all objects in real time. The collection mechanism involves generational replication, garbage collection, marking, and incremental garbage collection.

 

79. What is the basic principle of the garbage collector? Can the Garbage Collector recycle memory immediately? Is there any way to proactively notify virtual machines to recycle garbage?

For GC, when a programmer creates an object, GC starts to monitor the address, size, and usage of the object. Normally, GCRecording and management using Directed GraphsAll objects in heap. This method is used to determine which objects are "reachable" and which objects are "inaccessible ". When GC determines that some objects are "inaccessible", GC has the responsibility to recycle the memory space. Yes. Programmers can manually executeSystem. gc ()To notify the GC to run, but the Java language specification does not guarantee that the GC will be executed.

 

 

80. When to use assert.

Assertion is a common debugging method in software development. Many development languages support this mechanism. In implementation, assertion is a statement in the program. It checks a boolean expression. A correct program must ensure that the value of this boolean expression is true. If this value is false, it indicates that the program is already in an incorrect state, and assert will give a warning or exit. Generally,Assertion is used to ensure the most basic and critical correctness of the program.The assertion check is usually enabled during development and testing. To improve performance, the assertion check is usually disabled after the software is released.

PackageCom. huawei. interview;

 

PublicclassAssertTest {

 

/**

*@ ParamArgs

*/

Public static voidMain (String [] args ){

//TODOAuto-generated method stub

IntI = 0;

For(I = 0; I <5; I ++)

{

System.Out. Println (I );

}

// Assume that the program accidentally adds an additional sentence -- I;

-- I;

AssertI = 5;

}

 

}

 

81. Is there any memory leakage in java? Please briefly describe it.

Memory leakage means that an object or variable that is no longer used by the program is always occupied in the memory. Java has a garbage collection mechanism, which ensures that when an object is no longer referenced, that is, when the object is programmed as an orphan, the object will be automatically removed from the memory by the garbage collector. Because Java uses a directed graph for garbage collection management, it can eliminate the issue of reference loops. For example, there are two objects that are referenced by each other, as long as they are inaccessible to the root process, GC can also recycle them. For example, the following code shows the memory recycle in this case:

PackageCom. huawei. interview;

 

ImportJava. io. IOException;

 

PublicclassGarbageTest {

 

/**

*@ ParamArgs

*@ ThrowsIOException

*/

Public static voidMain (String [] args)ThrowsIOException {

//TODOAuto-generated method stub

Try{

GcTest();

}Catch(IOException e ){

//TODOAuto-generated catch block

E. printStackTrace ();

}

System.Out. Println ("hasexited gcTest! ");

System.In. Read ();

System.In. Read ();

System.Out. Println ("out begingc! ");

For(IntI = 0; I <100; I ++)

{

System.Gc();

System.In. Read ();

System.In. Read ();

}

}

 

Private static voidGcTest ()ThrowsIOException {

System.In. Read ();

System.In. Read ();

Person p1 =NewPerson ();

System.In. Read ();

System.In. Read ();

Person p2 =NewPerson ();

P1.setMate (p2 );

P2.setMate (p1 );

System.Out. Println ("beforeexit gctest! ");

System.In. Read ();

System.In. Read ();

System.Gc();

System.Out. Println ("exitgctest! ");

}

 

Private static classPerson

{

Byte[] Data =New byte[20000000];

Person mate =Null;

Public voidSetMate (Personother)

{

Mate = other;

}

}

}

 

Memory leakage in java:If a long-lived object holds a reference to a short-lived object, memory leakage is likely to occur.Although short-lived objects are no longer needed, they cannot be recycled because they hold their references. This is a scenario where memory leakage occurs in java, that is, the programmer may have created an object that will never be used again, but this object has been referenced, that is, this object is useless but cannot be recycled by the garbage collector, this is the possibility of Memory leakage in java. For example, in the cache system, we load an object and put it in the cache (for example, put it in a global map object), and never use it again, this object is always referenced by the cache but is no longer used.

Check for Memory leakage in java. Make sure that the program executes all the branches until the end of the program. Then, check whether an object has been used. If not, this object can be identified as Memory leakage.

 

If the method of an external class instance object returns an internal class instance object, this internal class object is referenced for a long time, even if the external class instance object is no longer used, however, because of the Instance Object of the internal class persistent external class, this external class object will not be reclaimed, which will also cause memory leakage.

 

The following content comes from the Internet (the main feature is to clear an element in the stack, not to completely remove it from the array, but to reduce the total number of storage, I can write better than this, when an element is removed, it will also disappear from the array. Set the value of the position of the element to null ):

I really can't think of a more classic example than that stack, so I want to reference other people's examples. The example below is not what I think, but what I see in the book. Of course, if I don't see it in the book, maybe I thought about it for a while, but at that time I said I did not believe it.

Public class Stack {
Private Object [] elements = new Object [10];
Private int size = 0;
Public void push (Object e ){
EnsureCapacity ();
Elements [size ++] = e;
}
Public Object pop (){
If (size = 0)

Throw new EmptyStackException ();
Return elements [-- size];
}
Private void ensureCapacity (){
If (elements. length = size ){
Object [] oldElements = elements;
Elements = new Object [2 * elements. length + 1];
System. arraycopy (oldElements, 0, elements, 0, size );
}
}
}
The above principle should be very simple. If the stack adds 10 elements and then all pops up, although the stack is empty and there is nothing we want, this is an object that cannot be recycled, this meets two conditions for Memory leakage: useless and irretrievable.

However, the existence of such a thing may not necessarily lead to any consequence. If this stack is used less often, several K of memory will be wasted. In any case, our memory is on G, where will there be any impact? Besides, this stuff will be recycled soon. What's the relationship. The following are two examples.

Example 1
Public class Bad {
Public static Stack s = Stack ();
Static {
S. push (new Object ());
S. pop (); // There is an object with Memory leakage.
S. push (new Object (); // The above Object can be recycled, so it is self-healing.
}
}
Because it is static, it always exists until the program exits, but we can also see that it has a self-healing function, that is, if your Stack has a maximum of 100 objects, in this case, at most 100 objects cannot be recycled. In fact, this should be easy to understand. The Stack holds 100 references internally. The worst case is that they are useless, because once we make a new move, the previous reference will naturally disappear!

 

Another scenario of Memory leakage: when an object is stored in a HashSet set, you cannot modify the fields of the object involved in calculating the hash value. Otherwise, the modified hash value of the object is different from the hash value originally stored in the HashSet set. In this case, even if the contains method uses the current reference of this object as the parameter to retrieve the object from the HashSet set, the result that the object cannot be found is returned, this will also cause the failure to delete the current object from the HashSet set, resulting in Memory leakage.

 

 

 

82. Can I write a class, also called java. lang. String?

 

Yes, but you need to use your own class loader to load the application. Otherwise, the system class loader will always just load the jre. the java. lang. string. Because in tomcat web applications, are by webapp Class Loader first loaded by themselves in the WEB-INF/classess Directory class, and then commission the parent class loader load, if we write a java. lang. string. At this time, the Servlet program loads java we write. lang. string. lang. all of the String classes will have problems.

 

Although java providesEndorsedTechnology can cover some classes in jdk. The specific approach is ..... However, the classes that can be overwritten have a limited scope. Classes in packages such as java. lang are not included.

 

(The following example is used to help you learn and understand the problem. Do not use it as part of the answer. Otherwise, people suspect that the question has been leaked.) For example, run the following program:

PackageJava. lang;

 

PublicclassString {

 

/**

*@ ParamArgs

*/

Public static voidMain (String [] args ){

//TODOAuto-generated method stub

System.Out. Println ("string ");

}

 

}

The reported error is as follows:

Java. lang. NoSuchMethodError: main

Exception inthread "main"

This is because the built-in java. lang. String of jre is loaded, and there is no main method in this class.

 

83. Java code error

1.
Abstract class Name {
Private String name;
Public abstract boolean isStupidName (String name ){}
}
What's wrong with this?
Answer: Yes. Abstract method must end with a semicolon without curly braces.
2.
Public class Something {
Void doSomething (){
Private String s = "";
Int l = s. length ();
}
}
Is it wrong?
Answer: Yes. You cannot place any access modifiers (private, public, and protected) before local variables ). Final can be used to modify local variables.
(Like abstract and strictfp, final is not an access modifier. strictfp can only modify class and method rather than variable ).
3.
Abstract class Something {
Private abstract String doSomething ();
}
Is there nothing wrong with this?
Answer: Yes. Abstract methods cannot be modified in private mode. Abstract methods is to make the sub-class implement (Implementation) specific details, how can I use private to abstract
What about method blocking? (Likewise, final cannot be added before abstract method ).
4.
Public class Something {
Public int addOne (final int x ){
Return ++ x;
}
}
This is obvious.
Answer: Yes. Int x is modified to final, meaning x cannot be modified in addOne method.
5.
Public class Something {
Public static void main (String [] args ){
Other o = new Other ();
New Something (). addOne (o );
}
Public void addOne (final Other o ){
O. I ++;
}
}
Class Other {
Public int I;
}
Similar to the above, they are all about final. Is this wrong?
Answer: Correct. In addOne method, the parameter o is modified to final. If we modify the reference of o in addOne method
(For example, o = new Other. But here we modify the member vairable of o.
(Member variable), and o's reference has not changed.
6.
Class Something {
Int I;
Public void doSomething (){
System. out. println ("I =" + I );
}
}
What's wrong? It cannot be seen.
Answer: Correct. The output is "I = 0 ". Int I belongs to instant variable (instance variable, or member variable ). Instant variable has default value. The default value of int is 0.
7.
Class Something {
Final int I;
Public void doSomething (){
System. out. println ("I =" + I );
}
}
Unlike the above question, there is only one more final. Is that true?
Answer: Yes. Final int I is a final instant variable (instance variable, or member variable ). The instant variable of final has no default value and must be assigned a clear value before the constructor ends. It can be changed to "final int I = 0 ;".
8.
Public class Something {
Public static void main (String [] args ){
Something s = new Something ();
System. out. println ("s. doSomething () returns" + doSomething ());
}
Public String doSomething (){
Return "Do something ...";
}
}
Looks perfect.
Answer: Yes. It seems that there is no problem with calling doSomething in main. After all, both methods are in the same class. But take a closer look, main is static. Static method cannot call non-staticmethods directly. You can change it to "System. out. println (" s. doSomething () returns "+ s. doSomething ());". Similarly, static method cannot access non-static instant variable.
9.
Here, the name of the Something class is OtherThing. java.
Class Something {
Private static void main (String [] something_to_do ){
System. out. println ("Dosomething ...");
}
}
This seems obvious.
Answer: Correct. No one has ever said that the Java Class name must be the same as its file name. However, the public class name must be the same as the file name.
10.
Interface {
Int x = 0;
}
Class B {
Int x = 1;
}
Class C extends B implements {
Public void pX (){
System. out. println (x );
}
Public static void main (String [] args ){
New C (). pX ();
}
}
Answer: incorrect. An error occurs during compilation (the error description varies with the JVM, which means that the unspecified x call matches both of them (just like importing java at the same time. util and java. when two SQL packages are declared, the Date is the same ). The variables of the parent class can be identified using super. x, and the interface property is implicitly public staticfinal by default. Therefore, A. x can be used to specify the variables.
11.
Interface Playable {
Void play ();
}
Interface Bounceable {
Void play ();
}
Interface Rollable extends Playable, Bounceable {
Ball ball = new Ball ("PingPang ");
}
Class Ball implements Rollable {
Private String name;
Public String getName (){
Return name;
}
Public Ball (String name ){
This. name = name;
}
Public void play (){
Ball = newBall ("Football ");
System. out. println (ball. getName ());
}
}
This error is not easy to find.
Answer: Yes. "InterfaceRollable extends Playable, Bounceable" no problem. The interface can inherit multiple interfaces, so this is correct. The problem lies in "Ball ball = new Ball (" PingPang ");" in interface Rollable ");". The default value of interface variable declared in the interface is public static final. That is to say, "Ball ball = new Ball (" PingPang ");" is actually "public staticfinal Ball = new ball (" PingPang ");". In the Play () method of the Ball class, "ball = newBall (" Football ");" changes the reference of the ball, and the ball here comes from the Rollable interface, the ball in Rollable interface is public static final, and the final object cannot be changed by reference. Therefore, the compiler will display errors in "ball = newBall (" Football.

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.