On learning Java interview questions

1, explanation of the memory stack (Stack), the use of the heap (heap) region and a method (method area) of.
answer:Usually we define a basic data types of variables, a reference to an object, there is on-site preservation of function calls use the stack space in the JVM; and objects created by the new keyword and constructor of the space on the heap, the heap is the main area of ​​the garbage collector management,Now that the garbage collectors are used generational collection algorithm, stack space may also be subdivided into the old generation and the new generation, then it can be divided into specific Eden, Survivor (and can be divided into From Survivor To Survivor), Tenured; the method and heap area are individual threads shared memory area for storing class information have been loaded in the JVM, constants, static variable, the JIT compiler to compile the code and other data; literal (literal) program such as direct writing of 100, "hello" and constants are on the constant pool, the pool is part of the constant region of the method. Stack space to operate the fastest but the stack is very small, usually a large number of objects are on the heap space, stack and heap size can be adjusted by the JVM startup parameters, run out of stack space will lead to StackOverflowError, while the heap and constant lack of pool space will lead to OutOfMemoryError.

String str = new String("hello");

The above statement str variable on the stack, create it with the new string object on the heap, and "hello" the literal method is on the area.

2, the array has no length () method? String has no length () method?
answer:No array length () method, length attributes. String has a length () method.
JavaScript, the length of the string was obtained by the length property, which is easily confused and Java.

3, the constructor (constructor) can be rewritten if (override)?
A: The constructor can not be inherited, and therefore can not be rewritten, but can be overloaded.

4, two objects the same value (x.equals (y) == true) , but it may have different hash code, this sentence right?
A: No,If two objects x and y satisfy x.equals (y) = true, hash code thereof (hash code) should be the same.
: Java For eqauls and hashCode method is specified in
(1) if two identical objects (Returns true equals method), then they must be the same hashCode value;
(2) if two objects have the same hashCode, they are not necessarily the same.
Of course, you may not want to follow it, but if you violate the above principles will find that when using the container, the same object can appear in the Set collection, while increasing the efficiency of the new elements will be greatly reduced (to use a hash storage the system, if the hash code of frequent conflict will result in a sharp decline in access performance).

5, can inherit String class?
A: String class is final class can not be inherited.

6, when an object is passed as a parameter to a method, this method can change the properties of this object, and returns the result of changes in, then in the end is passed by reference or value transfer here?
A: The value is passed.Java language method invocation only supports the value of the parameter passed. When a method is passed to the object instance as a parameter, the value of the parameter is a reference to the object. Properties of the object can be changed in the called procedure, but changes will not affect the object referenced by the caller. C ++ and C # may be transmitted or by-reference parameters to change the parameter values ​​passed. You may be written in C # code shown below, but can not do in Java.

7, String and StringBuilder, StringBuffer the difference?
A: Java platform provides two types of strings: String and StringBuffer / StringBuilder, which can store and manipulate strings. String string which is read-only, which means the contents of a string String references can not be changed. The String object StringBuffer / StringBuilder class representation may be modified directly. On the security thread, StringBuilder is not thread-safe, while StringBuffer is thread-safe, if a StringBuffer object is to use multiple threads in a string buffer, StringBuffer in many ways with the synchronized keyword, so you can guarantee thread is safe, but StringBuilder approach is not the key, it can not guarantee thread-safe, there may be something wrong operation occurs. So if you want to operate a multi-threaded, then we should use StringBuffer, but in single-threaded case, it is recommended to use the faster StringBuilder.

Applies to a small number of string manipulation: String
the StringBuilder: suitable for single-threaded operating a large number of cases in the character buffer
conduct a large number of suitable multi-threaded operating under the character buffer: StringBuffer

8, the difference between overloading (Overload) and rewritable (Override) is. Overloaded method can be differentiated according to the type of return?
A: == method overloading and rewriting are multi-state manner, except that it is implemented compile-time polymorphism, which polymorphism is achieved runtime. == overload occurs in a class, the method of the same name if there are different list of parameters (parameters of different types and different number of parameters or both) is considered overloaded; rewrite occurs child and parent class of Room subclasses override the requirement is overridden method with the parent class is overridden method with the same return type, method is overridden better access than the parent, can not be overridden parent class method declarations than more exceptions (in s substitution principle).Overloaded no special requirements for the return type.

Face questions: Huawei face questions are asked such a question - "Why can not distinguish overloaded based on return type," quick to tell you the answer!
Overloaded no special requirements for the return type

9, describe the principle mechanism JVM class document loading?
A: The JVM is loaded in the class by the class loader (ClassLoader) and its subclasses to achieve, in the Java class loader is an important component of the Java runtime system, which is responsible for finding and loading class at runtime file class.
As the cross-platform nature of Java, compiled Java source code is not an executable program, but one or more class files. When the program needs to use a Java class, JVM will ensure that the class has been loaded, the connection (verification, preparation and analytical) and initialization. Loading refers to the class of the data read in the .class file type into memory, usually creating an array of bytes read into .class files, and then generates the corresponding object class Class loaded. Once loaded, Class object is not complete, so in this case the class is not yet available. When after the class is loaded into the connection phase, this phase including verification, preparation (memory allocated as a static variable and set a default initial value) and parsing (replaced symbolic references to directly reference) three steps. Finally, the JVM class is initialized, comprising: 1) If there is a direct parent class and the class has not been initialized, then initialize the parent class; 2) if there is the class initialization statement, are sequentially performed on these initialization statements.
Loading classes by the class loader is completed, the class loader comprises: a loader root (BootStrap), extended loader (the Extension), the system loader (System) and user-defined class loader (in the java.lang.ClassLoader Subclass). Starting Java 2 (JDK 1.2), class loading process adopted father commissioned mechanism (PDM). PDM better guarantee the safety of the Java platform, in this mechanism, JVM comes is the root Bootstrap loader, loader other has one and only one parent class loader. Loading first class the parent class loader loads the request, the parent class loader when its inability self loading loader subclass. Bootstrap JVM does not provide a reference to the Java program. The following is a description of several classes loader:

Bootstrap: generally implemented using native code, is responsible for loading JVM basic core libraries (rt.jar);
the Extension: loading the library system java.ext.dirs attribute specified directory, its parent is loaded on Bootstrap;
the System: application of known class loader, a parent class Extension. It is the most widely used class loader. Classpath it from the environment variable or system attributes described java.class.path directory specified class, user-defined default parent loader loader.

10, char type variable can store a Chinese characters, and why?
A: char type can store a Chinese characters, because coding in Java using Unicode (do not select any particular encoding, just use the character number in the character set, which is a unified only way), a char type accounted for two words section (16-bit), so put a Chinese is no problem.

Added: Using Unicode means that the character in the JVM inside and outside have different manifestations, inside the JVM is Unicode, when the character is transferred from the internal to the external JVM (for example, stored in the file system), encoding conversion is needed. Therefore, there is Java byte stream and character stream, and the stream converter converting such InputStreamReader and OutputStreamReader stream between characters and byte streams, these two classes are the byte stream between the adapter class and character stream, assume a code conversion tasks; for C programmers to accomplish this probably depends on the transcoding union (union / union) feature shared memory to achieve.

11, abstract class (abstract class) and interfaces (interface) What are the similarities and differences?
answer:No abstract classes and interfaces can be instantiated, but the reference may be defined type of abstract classes and interfaces.If a class inherits an abstract class or implements an interface need to abstract methods to achieve all of them, otherwise the class still need to be declared as an abstract class. Interface more abstract than the abstract class, can be defined as an abstract class constructor can have abstract methods and specific methods, but can not define the interface and wherein the constructor methods are all abstract methods. Abstract class members can be private, default, protected, public, and interface are all members of the public. You can define an abstract class member variables, and member variables defined in the interface actually are constants. There are abstract methods of the class must be declared as an abstract class, abstract class may not have abstract methods.

12, a static nested class (Static Nested Class) and inner classes (Inner Class) different?
A: Static Nested Class is declared static (static) inner class, it can not rely on an external class instance is instantiated. Inner classes usually required to instantiate class is instantiated in the external

Interview questions - what place the following code will produce a compilation error?

class Outer {
    class Inner {}
    public static void foo() { new Inner(); }
    public void bar() { new Inner(); }
    public static void main(String[] args) {
        new Inner();
    }
}

Note: Creating a Java Central African static inner classes of objects to be dependent on its external object, the top face questions in foo and main methods are static methods, static methods no this, no that is the so-called external object, and therefore can not be create an internal class object, if you want to create an internal class object in a static method, you can do this:

    new Outer().new Inner();

13, Java will be a memory leak it, please describe simple.
A: Because there are theoretically Java garbage collection (GC) there will be no memory leaks (which is also widely used in Java is an important cause of server-side programming); however, in the actual development, there may be useless but reachable objects that can not be recovered GC, so will lead to memory leaks. Hibernate example of Session (cache) of the objects belonging to a consistent state, the garbage collector will not recover these objects, however, there may be garbage objects useless these objects, if not closed (Close) or empty (the flush) cache may lead to memory leaks. Example The following code would result in a memory leak.

import java.util.Arrays;
import java.util.EmptyStackException;

public class MyStack<T> {
    private T[] elements;
    private int size = 0;

    private static final int INIT_CAPACITY = 16;

    public MyStack() {
        elements = (T[]) new Object[INIT_CAPACITY];
    }

    public void push(T elem) {
        ensureCapacity();
        elements[size++] = elem;
    }

    public T pop() {
        if(size == 0) 
            throw new EmptyStackException();
        return elements[--size];
    }

    private void ensureCapacity() {
        if(elements.length == size) {
            elements = Arrays.copyOf(elements, 2 * size + 1);
        }
    }
}

The above code implements a stack (last-out (FILO)) structure, at first glance does not seem any obvious problems, it can even be through a variety of unit tests you write. However, one of the pop method, but there is a problem of memory leaks when an object on the stack we use pop pop method, the object will not be garbage collected, even though the program is no longer using a stack of references to these objects, because the internal stack maintains outdated references to these objects (obsolete reference). In language support garbage collection, the memory leak is very subtle, this memory leak is actually unconscious object remains. If an object reference is retained up unconscious, then the garbage collector does not deal with this subject, it will not deal with other objects in the object reference, even if only a few such objects may also cause a lot of objects to be excluded in addition to garbage collection, resulting in a significant impact on performance, it will lead to Disk Paging (physical memory and virtual memory swap hard disk data) in extreme cases, even cause OutOfMemoryError.

14, abstract (abstract) whether the method can simultaneously be static (static), it also is a local method (native), which can be synchronized whether modified?
A: can not. Abstract method needs to subclass overrides, and static methods can not be rewritten, so the two are contradictory. Native method is a method implemented by native code (e.g., C code), the abstract method is not implemented, and it is contradictory. synchronized methods and implementation details related to abstract method does not involve the implementation details, and therefore conflicting.

15, explained the difference between static variables and instance variables.
answer:Static variables are modified static modifier variables, also known as class variables, which belong to the class, does not belong to any object class, no matter how many objects to create a class static variable and only one copy in memory;Examples of variables must be dependent on an instance, you need to create an object before you can access to it through an object. Static variables can be implemented so that multiple objects shared memory.

Added: Java development, the context classes and tools usually have a lot of static members.

16, if you can make calls to non-static (non-static) method from within a static (static) method?
A: No, static methods can only access static member, because calling non-static method of first creating an object, the object may not be initialized when calling a static method.

17, how to achieve the target clone?
A: There are two ways:
1) implement the Cloneable interface and override clone () method of class Object;.
2) implements Serializable interface, cloned by serialization and deserialization of the objects, the real depth of the clones can be achieved. .

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class MyUtil {

    private MyUtil() {
        throw new AssertionError();
    }

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) throws Exception {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bout);
        oos.writeObject(obj);

        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bin);
        return (T) ois.readObject();

        // 说明:调用ByteArrayInputStream或ByteArrayOutputStream对象的close方法没有任何意义
        // 这两个基于内存的流只要垃圾回收器清理对象就能够释放资源,这一点不同于对外部资源(如文件流)的释放
    }
}

Here is the test code:

import java.io.Serializable;

/**
 * 人类
 * @author 骆昊
 *
 */
class Person implements Serializable {
    private static final long serialVersionUID = -9102017020286042305L;

    private String name;    // 姓名
    private int age;        // 年龄
    private Car car;        // 座驾

    public Person(String name, int age, Car car) {
        this.name = name;
        this.age = age;
        this.car = car;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
    }

}
/**
 * 小汽车类
 * @author 骆昊
 *
 */
class Car implements Serializable {
    private static final long serialVersionUID = -5713945027627603702L;

    private String brand;       // 品牌
    private int maxSpeed;       // 最高时速

    public Car(String brand, int maxSpeed) {
        this.brand = brand;
        this.maxSpeed = maxSpeed;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    @Override
    public String toString() {
        return "Car [brand=" + brand + ", maxSpeed=" + maxSpeed + "]";
    }

}
class CloneTest {

    public static void main(String[] args) {
        try {
            Person p1 = new Person("Hao LUO", 33, new Car("Benz", 300));
            Person p2 = MyUtil.clone(p1);   // 深度克隆
            p2.getCar().setBrand("BYD");
            // 修改克隆的Person对象p2关联的汽车对象的品牌属性
            // 原来的Person对象p1关联的汽车不会受到任何影响
            // 因为在克隆Person对象时其关联的汽车对象也被克隆了
            System.out.println(p1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Note: Based on cloning serialization and de-serialization to achieve not only the depth of cloning, more importantly, is limited by generics, you can check out if you want to clone objects support serialization, this check is complete compiler, not in Throws abnormal operation, this scheme is much better than the method using the clone clone Object class. Let problems at compile time exposed always better to leave the matter to the runtime.

Published 444 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/zt2650693774/article/details/104984621