Java interview questions compulsory 50 (with answers) 1

The following content is the original and most recent set of Java interview questions and answers were responsible topics and answers given after a comprehensive revision, relatively classic, I believe that prepare recruits Java programmers must be beneficial.

Java programmers face questions set (1-50)

A, Java Fundamentals

1, object-oriented features have what?

A: The object-oriented features mainly in the following areas:

1) Abstract: Abstract is to sum up the common features of a process of constructing a class object class, data abstraction and include both behavioral abstraction. Only concerned with abstract objects which have attributes and behaviors, not concerned about the details of what these behaviors yes.

2) Inheritance: Inheritance is the process of creating a new class of information to be inherited from an existing class. Provide information inherited class is called the parent class (superclass, base class); information be inherited class is called a subclass (derived classes). Inheritance allows a software system changes in a certain continuity, while inheriting an important means of variable factors also package the program (if not understand, please read "Java and model," or "design patterns refined solution" Yan Hongbo disabilities regarding part of the bridge mode).

3) Package: encapsulation is generally considered a method of operating data and bind data, access to the data only via the defined interfaces. Object-oriented nature of the real world is portrayed as a series of fully autonomous, closed objects. Our method is written in a class implementation details of a packaging; we write a class that encapsulates the data and operations. We can say that the package is to hide all hide things, to provide the most simple programming interface (think of the difference can be ordinary washing machine and fully automatic washing machines, automatic washing machines significantly better package and therefore easier to operate only to the outside world; we now use smartphone package was also good enough, because a few buttons to get everything).

4) Polymorphism: polymorphism refers to allow objects of different sub-types respond differently to the same message. Simply put, it is to call the same method but do different things with the same object reference. Polymorphism Polymorphism Polymorphism is divided into compile-time and run when. If the method of the object viewed as an object to provide service to the outside world, then the run-time polymorphism can be interpreted as: When A system to access services provided by the system B, B system has a variety of ways to provide services, but all of A systems are transparent (as if the electric shaver is a system which is the system power supply system B, system B can be used with AC or battery-powered, they may even be solar, will only be passed class B a power supply object calls methods, but did not know the underlying supply system to achieve what is, exactly how gained momentum through). Method overloading (overload) is implemented compile-time polymorphism (also called pre-binding), and method overrides (override) to achieve polymorphism (also called a binding post) runtime. Run-time polymorphism is the essence of an object-oriented best thing to achieve polymorphism need to do two things: 1. A method of rewriting (subclass inherits the parent class and the parent class has or abstract method overrides); 2 object modeling (referenced by the parent type reference subtype object, so the same reference to the same method call will exhibit different behavior depending on the subclass objects).

 

2, access modifiers public, private, protected, and when the difference is not write (default)?

A: The differences are as follows:

The scope of the current class with other classes buns

public        √        √       √      √

protected  √        √       √      ×

default       √       √       ×      ×

private       √        ×      ×      ×

The default is default when members of the class do not write access modifications. The default for the same package disclosed in other classes corresponding to (public), a packet is not the same for the other classes as a private (private). Protected (protected) subclass equivalent public, not the same kind of parent-child relationship is not the package as a private.

 

3, String is the most basic data type?

Answer: It is not. The basic data type in Java only 8: byte, short, int, long, float, double, char, boolean; in addition to the basic types (primitive type) and enumerated types (enumeration type), and the rest are reference types ( reference type).

 

4, float f = 3.4; correct?

Answer: Incorrect. 3.4 is a double precision number, the double (double) assigned to the floating-point (float) belonging to the next transition (down-casting, also referred to as narrowing) will cause loss of precision, it is necessary cast float f = (float ) 3.4; or written float f = 3.4F ;.

 

5, short s1 = 1; s1 = s1 + 1; wrong it short s1 = 1;? S1 + = 1; wrong?

A: For short s1 = 1; s1 = s1 + 1; int Since the type 1 is, therefore s1 + 1 calculation result is an int, need to be assigned to the type of cast short type. And short s1 = 1; s1 + = 1; compile correctly, since s1 + = 1; corresponds to s1 = (short) (s1 + 1); wherein there are implicit cast.

 

6, Java has no goto?

A: goto is a reserved word in Java, it is not used in the current version of Java. (Given in Appendix prepared by James Gosling (Java father) "The Java Programming Language" book in a Java keyword list, including goto and const, but these two are the keyword is not running, so some places call it a reserved word, the word is actually reserved words should have a broader sense, because the familiar C language programmer knows that there is a special significance in the system library used the word or combination of words are is regarded as a reserved word)

 

7, int and Integer What is the difference?

A: Java is a nearly pure object-oriented programming language, but in order to facilitate the programming or introduced into the basic data type of the object, but in order to be able to these basic data types as object operation, Java for each elementary data types introduced corresponding type of packaging (wrapper class), int wrapper class is Integer, beginning from introduction of the JDK 1.5 automatic boxing / unboxing mechanism, so that the two can be interchangeable.

Java provides a package type for each primitive type:

Primitive types: boolean, char, byte, short, int, long, float, double

Package Type: Boolean, Character, Byte, Short, Integer, Long, Float, Double

 

com.lovo package;  
 // asked hovertree.com
public class AutoUnboxingTest {  
  
    public static void main(String[] args) {  
        Integer a = new Integer(3);  
        Integer b = 3; // will automatically packing into 3 types Integer  
        int c = 3;  
        System.out.println (a == b); // false two references do not reference the same object  
        System.out.println (a == c); // true a further automatic unpacking an int and c Comparison  
    }  
}

 

NOTE: a recently encountered interview questions, and is also related to the automatic boxing and unboxing code as follows:

 

public class Test03 {  
  
    public static void main(String[] args) {  
        Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;  
          
        System.out.println(f1 == f2);  
        System.out.println(f3 == f4);  
    }  
}  
// hovertree.com

 

If you uninformed easy to think that the two outputs are either all true or false. Note that the first f1, f2, f3, f4 four variables are Integer object, so the following is not the == operator to compare values ​​but reference. What is the nature of boxing is it? When we give an Integer object is assigned an int value will call the static method valueOf Integer class, if valueOf look at the source code to know what happened.

public static Integer valueOf(int i) {  
        if (i >= IntegerCache.low && i <= IntegerCache.high)  
            return IntegerCache.cache[i + (-IntegerCache.low)];  
        return new Integer(i);  
    }  
// hovertree.com

Integer class is an internal IntegerCache, which code is as follows:

 

/** 
     * Cache to support the object identity semantics of autoboxing for values between 
     * -128 and 127 (inclusive) as required by JLS. 
     * 
     * The cache is initialized on first usage.  The size of the cache 
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. 
     * During VM initialization, java.lang.Integer.IntegerCache.high property 
     * may be set and saved in the private system properties in the 
     * sun.misc.VM class. 
 * hovertree.com

     */  
  
    private static class IntegerCache {  
        static final int low = -128;  
        static final int high;  
        static final Integer cache[];  
  
        static {  
            // high value may be configured by property  
            int h = 127;  
            String integerCacheHighPropValue =  
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");  
            if (integerCacheHighPropValue != null) {  
                try {  
                    int i = parseInt(integerCacheHighPropValue);  
                    i = Math.max(i, 127);  
                    // Maximum array size is Integer.MAX_VALUE  
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);  
                } catch( NumberFormatException nfe) {  
                    // If the property cannot be parsed into an int, ignore it.  
                }  
            }  
            high = h;  
  
            cache = new Integer[(high - low) + 1];  
            int j = low;  
            for(int k = 0; k < cache.length; k++)  
                cache[k] = new Integer(j++);  
  
            // range [-128, 127] must be interned (JLS7 5.1.7)  
            assert IntegerCache.high >= 127;  
        }  
  
        private IntegerCache() {}  
    }

 

Simply put, if the literal value between -128 and 127, then no new object is new Integer, Integer object but directly references the constant pool, the upper face questions result is f1 == f2 true, the result f3 == f4 is false. The more the more seemingly simple questions which face the mystery, we need to interview those who have a considerable degree of skill.

8, & and && difference?

 

A: & operator in two ways: (1) bit and; (2) a logical AND. && operator is shorted and operation. Logic and with short circuit and the difference is very great, although both left and right ends requires operators Boolean values ​​are true value of the entire expression is true. && is called short-circuit operation is because, if the value of the expression on the left && is false, the expression on the right will be directly shorted out, it will not carry out operations. Many times we may need to use & && rather than, for example, determine the username is not null and not an empty string when you log in to authenticate the user, should be written as:! Username = null && username.equals ( ""), both! order can not be exchanged, but can not use the & operator, because if the first condition is not satisfied, equals the string can not be compared or will cause a NullPointerException. Note: Logical OR operator (|) and short circuit or operator (||) of the difference as well.

NOTE: If you are familiar with JavaScript, you may feel more powerful short-circuit operation, JavaScript want to become a master of the short-circuit operation will start with the Fun begin.

 http://hovertree.com/menu/java/

9, explanation memory stack (stack), the use of the heap (heap) and static storage area.

A: Usually a basic data types of variables, we define an object reference, there is the scene function calls are stored in the memory stack space use; and objects created by the new keyword and constructor on the heap space; program the literal (literal), such as direct-write 100, "hello" and constants are placed in the static storage area. Stack space operations fastest but also very small, usually a large number of objects are on the heap space, the entire memory, including virtual memory on the hard disk space can be used as piles.

String str = new String(“hello”);

The above statement str on the stack, created out of a new string object on the heap, and "hello" in the literal static storage area.

Added: Use a newer version of Java, called an "escape analysis" technology, a number of local objects can be placed on the stack in order to improve the operational performance of the object.

 

10, Math.round (11.5) is equal to how much? Math.round (-11.5) equals how much?

A: Math.round (11.5) return value is 12, Math.round (-11.5) returns the value -11. Rounding principle is applied on the parameter and then 0.5 under rounding.

Guess you like

Origin blog.csdn.net/qq_39581763/article/details/93715532