In the last 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 basis of the foundation, 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 easy first and then difficult. The material is still behind. Continue to pay attention. Continuing with the 70 questions mentioned last time, this chapter will prepare 13 classic questions for children's shoes
71. Name some commonly used classes, packages and interfaces. Please give five each
To make people feel that you are familiar with java ee development, you should not only list the things in core java, but also list the things involved in ssh projects. Just 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
Commonly used package: 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 to inherit. Please tell us which classes they are respectively?
Byte stream, character stream. Byte stream inherits from InputStream OutputStream, and character stream inherits from InputStreamReaderOutputStreamWriter. In Java There are many other streams in the IO package, mainly to improve performance and ease of use.
73. Difference between byte stream and character stream
To output a piece of binary data to a device one by one, or read a piece of binary data from a device one by one, no matter what the input and output device is, we should complete these operations in a unified way and describe them in an abstract way, which is called IO flow, The corresponding abstract classes are OutputStream and InputStream. Different implementation classes represent different input and output devices, which operate on bytes.
In applications, it is often necessary to output or read in a text that is completely character. Is it OK to use byte stream? Everything in the computer eventually exists in the form of binary bytes. For "China" characters, first get their corresponding bytes, and then write the bytes to the output stream. When reading, we first read bytes, but we need to display them as characters. We need to convert bytes into characters. Because of such a wide range of needs, people specially provide the packaging class of character 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 and then write. Character stream is the packaging of byte stream, while character stream directly accepts strings. It converts strings into bytes and writes them to the underlying device, which provides a little convenience for us to write or read strings to IO devices.
When converting characters to bytes, pay attention to the problem of encoding, because the string is converted into a byte array,
In fact, it is a byte form of some kind of coding converted to the character, and reading is the opposite.
Code case explaining the relationship between byte stream and character 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[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 it? Or please explain the function of the Serializable interface.
Sometimes we transfer a Java object into a byte stream or restore it from a byte stream to a Java object. For example, to store the Java object on the hard disk or transfer it to other computers on the network, we can write our own code to turn a Java object into a byte stream of a certain format and then transmit it, jre itself provides this support. We can call the writeObject method of OutputStream to do it. If we want java to do it for us, the object to be transmitted must implement the serializable interface. In this way, special processing will be carried out during javac compilation, and the compiled class can be operated by the writeObject method. This is the so-called serialization. The class that needs to be serialized must implement the serializable interface, which is a mini interface, in which there is no method to be implemented. implementsSerializable is only to mark that the object can be serialized.
For example, in web development, if the object is saved in Session and tomcat wants to serialize the Session object to the hard disk when restarting, the object must implement the Serializable interface. If the object needs to be transmitted through the distributed system or called remotely through rmi, it needs to transmit the object on the network, and the transmitted object must implement the Serializable interface.
75. Describe the principle and mechanism of loading class files by JVM?
Class loading in JVM is realized by ClassLoader and its subclasses. Java ClassLoader is an important component of Java runtime system. It is responsible for finding and loading classes in class files at run time.
76. What is the difference between heap and stack.
java memory is divided into two types: stack memory and heap memory. Stack memory means that when a program enters a method, it will allocate a private storage space for the method to store local variables inside the method. When the method ends, the stack allocated to the method will be released, and the variables in the stack will be released accordingly.
Heap is a memory different from stack. It is generally used to store those data that are not placed in the current method stack. For example, objects created with new are placed in the heap, so it will not disappear with the end of the method. After the local variables in the method are decorated with final, they are placed in the heap instead of the stack.
77. What is GC? Why GC?
GC means garbage collection. Memory processing is a place where programmers are prone to problems. Forgetting or wrong memory recycling will lead to instability or even crash of programs or systems. The GC function provided by java can automatically monitor whether objects exceed the operating domain, so as to achieve the purpose of automatic memory recycling, The Java language does not provide a display operation method to free allocated memory.
78. Advantages and principles of waste recycling. Two recovery mechanisms are considered.
A remarkable feature of Java language is the introduction of garbage collection mechanism, which solves the most troublesome problem of memory management for c + + programmers. It makes Java programmers no longer need to consider memory management when writing programs. Due to a garbage collection mechanism, objects in Java no longer have the concept of "scope", and only object references have "scope". Garbage collection can effectively prevent memory leakage and effectively use available memory. The garbage collector usually runs as a separate low-level thread to clear and recycle the objects that have died or have not been used for a long time in the memory heap under unpredictable circumstances. Programmers cannot call the garbage collector to garbage collect one or all objects in real time. The recycling mechanism includes generational replication garbage collection, marked garbage collection and incremental garbage collection.
79. What is the basic principle of garbage collector? Can the garbage collector reclaim memory right away? Is there any way to actively notify the virtual machine for garbage collection?
For GC, when the programmer creates an object, GC starts to monitor the address, size and usage of the object. Generally, GC records and manages all objects in the heap in the form of directed graph. In this way, you can determine which objects are "reachable" and which objects are "unreachable". When the GC determines that some objects are "unreachable", the GC has the responsibility to reclaim these memory spaces. sure. Programmers can manually execute system GC () tells GC to run, but the Java language specification does not guarantee that GC will execute.
80. When to use assert.
Assertion is a common debugging method in software development, which is supported by many development languages. In the implementation, assertion is a statement in the program, which checks a boolean expression. A correct program must ensure that the value of the boolean expression is true; If the value is false, it indicates that the program is in an incorrect state, and assert will give a warning or exit. Generally speaking, assertion is used to ensure the most basic and critical correctness of the program. The assertion check is usually turned on during development and testing. To improve performance, the assertion check is usually turned off after the software is released.
package com.huawei.interview; publicclass AssertTest { /** * @paramargs */ public static voidmain(String[] args) { // TODO Auto-generated method stub int i = 0; for(i = 0; i < 5; i++) { System.out.println(i); } //Suppose the program accidentally added one more sentence--i; --i; assert i == 5; } }
81. Is there a memory leak in java? Please briefly describe it.
The so-called memory leak means that an object or variable that is no longer used by the program has been occupied in memory. Java has a garbage collection mechanism, which can ensure that when an object is no longer referenced, that is, when the object is orphaned, the object will be automatically cleared from memory by the garbage collector. Because Java uses directed graph for garbage collection management, the problem of reference cycle can be eliminated. For example, there are two objects that reference each other. As long as they are unreachable to the root process, GC can also recycle them. For example, the following code can see the memory recycling in this case:
Memory leakage in java: if an object with a long life cycle holds a reference to an object with a short life cycle, memory leakage is likely to occur. Although the object with a short life cycle is no longer needed, it cannot be recycled because the object with a long life cycle holds its reference. This is the scenario of memory leakage in java. Generally speaking, That is, the programmer may create an object and never use it in the future, but the object is always referenced, that is, the object is useless but cannot be recycled by the garbage collector. This is the possible memory leakage in java. For example, in the cache system, we load an object and put it in the cache (for example, in a global map object), Then it is never used again. This object is always referenced by the cache, but it is no longer used.package com.huawei.interview; import java.io.IOException; publicclass GarbageTest { /** * @paramargs * @throwsIOException */ public static voidmain(String[] args) throws IOException { // TODO Auto-generated method stub try { gcTest(); } catch(IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("hasexited gcTest!"); System.in.read(); System.in.read(); System.out.println("out begingc!"); for(int i = 0; i < 100; i++) { System.gc(); System.in.read(); System.in.read(); } } private static voidgcTest() throws IOException { System.in.read(); System.in.read(); Person p1 = new Person(); System.in.read(); System.in.read(); Person p2 = new Person(); 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 void setMate(Personother) { mate = other; } } }
Check the memory leak in java. Be sure to let the program complete all branches until the end of the program, and then see whether an object has been used. If not, it can be determined that the object belongs to memory leak.
If the method of an instance object of an external class returns an instance object of an internal class, the internal class object is referenced for a long time. Even if the external class instance object is no longer used, because the internal class persists the instance object of the external class, the external class object will not be garbage collected, which will also cause memory leakage.
The following content comes from the Internet (the main feature is to empty 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 removing an element, let it disappear from the array by the way, and set the value of the location of that element to null):
I really can't think of a more classic example than that stack, so I have to quote other people's examples. The following examples are not what I thought of, but what I saw in the book. Of course, if I didn't see it in the book, I might think of it myself for a while, but at that time, I said I thought of it myself and no one believed it.
The above principle should be very simple. If 10 elements are added to the stack and all pop up, although the stack is empty and there is nothing we want, this is an object that cannot be recycled, which meets the two conditions of memory leakage: useless and unrecoverable.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); } } }
However, even the existence of such things does not necessarily lead to any consequences. If the stack is used less, it will waste a few K memory. Anyway, our memory is on G. what will be the impact? Besides, this thing will be recycled soon. What does it matter. Here are two examples.
Example 1
public class Bad { public static Stack s = Stack(); static { s.push(new Object()); s.pop(); //There is a memory leak in an object s.push(new Object()); //The above objects can be recycled, which is equivalent to self-healing } }
Because it is static, it will exist until the program exits, but we can also see that it has self-healing function. That is, if your Stack has at most 100 objects, then at most only 100 objects cannot be recycled. In fact, it should be easy to understand that there are 100 references in the Stack. The worst case is that they are useless, because once we put new objects, Previous references disappear naturally!
Another case of memory leakage: after an object is stored in the HashSet set, the fields in the object that participate in the calculation of hash value cannot be modified. Otherwise, the hash value of the object after modification 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 the object as a parameter to retrieve the object in the HashSet set set, it will return the result that the object cannot be found, which will lead to the failure to delete the current object separately from the HashSet set set set, resulting in memory leakage.
82. Can you write your own class, also known as Java lang.String?
Yes, but in the application, you need to use your own class loader to load. Otherwise, the class loader of the system will only load JRE The Java. Jar package lang.String. In tomcat's web applications, webapp's own class loader loads the classes in the WEB-INF/classess directory first, and then entrusts the superior class loader to load them. If we write a Java Lang. string. At this time, the Servlet program loads Java. String written by ourselves Lang. string, but doing so will cause many potential problems. It turns out that all use Java Lang. string class will have problems.
Although java provides endorsed technology, which can cover some classes in jdk, the specific method is. However, the classes that can be covered have a limited scope, excluding java Lang is a class in a package like this.
(the following example is mainly for the convenience of learning and understanding. It should not be used as part of the answer. Otherwise, it is suspected that the title has been leaked.) for example, run the following program:
The errors reported are as follows:package java.lang; publicclass String { /** * @paramargs */ public static voidmain(String[] args) { // TODO Auto-generated method stub System.out.println("string"); } }
java.lang.NoSuchMethodError:main Exception inthread "main" This is because it is loaded jre Self contained java.lang.String,Not in this category main method.
83. Java code error checking
1.
abstract class Name { private String name; public abstract boolean isStupidName(String name) {} }
Heroes, what's wrong with this?
Answer: wrong. abstract method must end with a semicolon without curly braces.
2.
public class Something { void doSomething () { private String s = ""; int l = s.length(); } }
Is there anything wrong?
Answer: wrong. No access modifiers (private, public, and protected) can be placed before local variables. final can be used to modify local variables
(final, like abstract and strictfp, are non access modifiers. Strictfp can only modify class and method, not variable).
3.
abstract class Something { private abstract String doSomething (); }
Doesn't that seem to be wrong?
Answer: wrong. Abstract methods cannot be decorated with private. The methods of abstract are to let the subclass implement specific details. How can we use private to implement abstract
Method is blocked? (similarly, final cannot be added before abstract method).
4.
public class Something { public int addOne(final int x) { return ++x; } }
This is obvious.
Answer: wrong. int x is modified to final, which means that 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();), Then, as in the previous example, this question is also wrong. But the member vairable of O is modified here
(member variable), while the reference of o has not changed.
6.
class Something { int i; public void doSomething() { System.out.println("i = "+ i); } }
What's wrong? I can't see it.
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); } }
There is only one difference from the above question, that is, there is one more final. Is that wrong?
answer:
wrong. final int i is a final instant variable (instance variable, or member variable). Final instant
variable has no default value and must be given an explicit value before the end of the constructor. It can be modified 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 ..."; } }
It looks perfect.
answer:
wrong. It looks like call ing in main
There is no problem with doSomething. After all, both methods are in the same class. But look closely. main is static. static
method cannot be call ed directly
non-staticmethods. It can be changed to "System.out.println("s.doSomething()returns "+
s.doSomething()); ". similarly, static method cannot access non static instant variable.
9.
Here, the file of Something class is called 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 Java's Class name must be the same as its file name. However, the name of public class must be the same as the file name.
10.
interface A{ int x = 0; } class B{ int x =1; } class C extends B implements A { public void pX(){ System.out.println(x); } public static void main(String[] args) { new C().pX(); } }
Answer: wrong. Errors will occur during compilation (different JVM s with different error descriptions have different information, which means that x is not explicitly called, and both X match (just like directly declaring Date when importing java.util and java.sql packages at the same time). For variables of the parent class, you can use super X, and the default attribute of the interface is public staticfinal Therefore, it can be clarified through A.x.
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 mistake is not easy to find.
answer:
wrong. "interfaceRollable extends Playable,
Bounceable "no problem. Interface can inherit multiple interfaces, so that's right here. The problem is interface
"Ball ball =new Ball("PingPang ");" in Rollable. Any interface declared in the interface
Variable (interface variable, also known as member variable), which defaults to public static final. That is, "Ball ball = new"
Ball("PingPang"); "Actually" public staticfinal ball = New
Ball("PingPang"); "In the Play() method of the ball class," ball said=
newBall("Football"); "Changed the reference of the ball, and the ball here comes from Rollable
Interface, the ball in the Rollable interface is public static
Final, final object s cannot be changed reference. So the compiler will=
newBall("Football"); "There are errors displayed here.