Collected some interview questions

I just came out of the training course system, and I also began to face the real need to step into the circle of programmers when looking for a job.
Recently, I have been busy doing resumes, reviewing basic knowledge, and then starting to submit resumes and interviews. The pressure is quite high, I'm worried that I can't do it well. They all say that it's because I don't have enough experience, so I'm relatively immature. If I have more experience, I'll become proficient. I hope so. Come on! I've
found some interview questions for the time being, and collected them first.
1. Object-oriented What are the characteristics of the object?
Answer: The characteristics of object-oriented mainly include the following aspects:
1) Abstraction: Abstraction is the process of summarizing the common characteristics of a class of objects to construct a class, including data abstraction and behavioral abstraction. Abstraction only focuses on what properties and behaviors an object has, not on the details of those behaviors.
2) Inheritance: Inheritance is the process of creating a new class by obtaining inheritance information from an existing class. A class that provides inheritance information is called a parent class (superclass, base class); a class that obtains inheritance information is called a subclass (derived class). Inheritance makes the changing software system have a certain continuity, and inheritance is also an important means to encapsulate the variable factors in the program (if you can't understand it, please read Dr. Yan Hong's "Java and Patterns" or "Design Patterns Explanation" about part of the bridge mode).
3) Encapsulation: It is generally considered that encapsulation is to bind the data and the methods of operating the data, and the access to the data can only be through the defined interface. The essence of object orientation is to represent the real world as a series of completely autonomous, closed objects. The methods we write in a class are an encapsulation of implementation details; the encapsulation of data and data operations when we write a class. It can be said that packaging is to hide everything that can be hidden, and only provide the simplest programming interface to the outside world (you can think of the difference between ordinary washing machines and fully automatic washing machines, obviously fully automatic washing machines are better packaged and therefore easier to operate; we now use 's smartphones are also well packaged, because a few buttons do everything).
4) Polymorphism: Polymorphism refers to allowing objects of different subtypes to respond differently to the same message. Simply put, it calls the same method with the same object reference but does different things. Polymorphism is divided into compile-time polymorphism and run-time polymorphism. If the method of the object is regarded as the service provided by the object to the outside world, then the polymorphism at runtime can be explained as: when the system A accesses the service provided by the system B, the system B has multiple ways to provide the service, but everything affects the A system. The system is transparent (just like the electric shaver is system A, its power supply system is system B, system B can be powered by batteries or AC, or even solar energy, system A will only pass through Class B The object calls the power supply method, but does not know what the underlying implementation of the power supply system is and how it gets power). Method overloading (overload) achieves compile-time polymorphism (also known as front binding), and method override (override) achieves run-time polymorphism (also known as back binding). Runtime polymorphism is the most quintessential object-oriented thing. To achieve polymorphism, two things need to be done: 1. Method rewriting (subclass inherits the parent class and overrides the existing or abstract methods in the parent class); 2. . Object modeling (use the parent type reference to refer to the subtype object, so that the same reference calls the same method will show different behaviors according to the subclass object)
2. Access modifiers public, private, protected, and do not write (default)?
Answer: The difference is as follows:
the scope of the current class is the same as the package subclass other
public √ √ √ √
protected √ √ √ ×
default √ √ × ×
private √ × × ×
The members of the class are defaulted to default when they are not modified by write access. By default, it is equivalent to public (public) for other classes in the same package, and equivalent to private (private) for other classes not in the same package. Protected (protected) is equivalent to public to subclasses, and equivalent to private to classes that are not in the same package and have no parent-child relationship.

3. Is String the most basic data type?
Answer: No. There are four basic data types in Java:
1 logical type boolean
2 text type char
3 integer type (byte, short, int, long)
4 floating point type (float, double)

4. Is float f=3.4; correct?
Answer: Not correct. 3.4 is a double-precision number. Assigning a double-precision type (double) to a floating-point type (float) is down-casting (also known as narrowing), which will cause precision loss, so it needs to be cast to float f = (float )3.4; or as float f = 3.4F;.

5. Is short s1 = 1; s1 = s1 + 1; wrong? short s1 = 1; s1 += 1; is wrong?
Answer: For short s1 = 1; s1 = s1 + 1; , so the result of s1+1 operation is also int type, which needs to be cast to short type. And short s1 = 1; s1 += 1; compiles correctly because s1+= 1; is equivalent to s1 = (short)(s1 + 1); which has an implicit cast.

7. What is the difference between int and Integer?
Answer: Java is a nearly pure object-oriented programming language, but for the convenience of programming, it still introduces basic data types that are not objects, but in order to be able to operate these basic data types as objects, Java is Each basic data type introduces a corresponding wrapper class. The wrapper class of int is Integer. Since JDK 1.5, an automatic boxing/unboxing mechanism has been introduced, so that the two can be converted to each other.
Java provides wrapper types for each primitive type:
Primitive types: boolean, char, byte, short, int, long, float, double
Wrapper types: Boolean, Character, Byte, Short, Integer, Long, Float, Double

8. What is the difference between & and &&?

Answer: The & operator can be used in two ways: (1) bitwise AND; (2) logical AND. The && operator is a short-circuit AND operation. The difference between logical and and short-circuit and is very huge, although both require that the Boolean values ​​on the left and right ends of the operator are both true. The value of the entire expression is true. The reason why && is called a short-circuit operation is that if the value of the expression on the left of && is false, the expression on the right will be directly short-circuited and no operation will be performed. In many cases, we may need to use && instead of &. For example, when verifying user login, it is determined that the username is not null and not an empty string. It should be written as: username != null &&!username.equals(""), the two The order cannot be exchanged, and the & operator cannot be used, because if the first condition does not hold, the equals comparison of strings cannot be performed at all, otherwise a NullPointerException will be generated. Note: The same is true for the difference between the logical OR operator (|) and the short-circuit OR operator (||).

11. Can switch work on byte, long, and String?
Answer: In the early JDK, in switch (expr), expr can be byte, short, char, or int. Since version 1.5, enumeration type (enum) has been introduced in Java, expr can also be an enumeration, and since JDK version 1.7, it can also be a string (String). Long is not allowed.

13. Does an array have a length() method? Does a String have a length() method?
Answer: Arrays do not have a length() method, but have the property of length. String has a length() method. In JavaScript, the length of a string is obtained through the length property, which is easy to confuse with Java.

14. In Java, how to get out of the current multiple nested loop?
Answer: Add a mark such as A before the outermost loop, and then use break A; to jump out of multiple loops. (Labeled break and continue statements are supported in Java, and function somewhat like goto statements in C and C++, but just like gotos are to be avoided, labeled break and continue should be avoided because it won't make your Programs become more elegant, and many times even have the opposite effect, so this syntax is actually better)

15. Can a constructor be overridden?
Answer: A constructor cannot be inherited, so it cannot be overridden, but it can be overloaded.

17. Can the String class be inherited?
Answer: The String class is a final class and cannot be inherited.

18. When an object is passed as a parameter to a method, the method can change the properties of the object and return the changed result. Is it pass-by-value or pass-by-reference?
Answer: Pass-by-value. The Java programming language only has pass-by-value parameters. When an object instance is passed as a parameter to a method, the value of the parameter is a reference to the object. The properties of the object can be changed during the calling process, but the reference to the object is never changed. In C++ and C#, the value of an incoming parameter can be changed by passing a reference or passing a parameter out.

20. The difference between Overload and Override. Can overloaded methods be distinguished according to their return types?
Answer: Method overloading and rewriting are both ways to achieve polymorphism. The difference is that the former implements polymorphism at compile time, while the latter implements runtime polymorphism. polymorphism. Overloading occurs in a class. If a method with the same name has a different parameter list (different parameter types, different number of parameters, or both), it is considered overloaded; overriding occurs between the subclass and the superclass, Overriding requires that the overridden method of the subclass has the same return type as the overridden method of the parent class, is more accessible than the overridden method of the parent class, and cannot declare more exceptions than the overridden method of the parent class (Richard Code). change the principle). Overloading has no special requirements on the return type.

23. What are the similarities and differences between abstract classes and interfaces?
Answer: Neither abstract classes nor interfaces can be instantiated, but references to abstract classes and interface types can be defined. If a class inherits an abstract class or implements an interface, it needs to implement all the abstract methods in it, otherwise the class still needs to be declared as an abstract class. Interfaces are more abstract than abstract classes, because abstract classes can define constructors, abstract methods and concrete methods, while interfaces cannot define constructors and all the methods are abstract methods. Members in abstract classes can be private, default, protected, and public, while members in interfaces are all public. Member variables can be defined in abstract classes, while those defined in interfaces are actually constants. A class with abstract methods must be declared abstract, and abstract classes do not necessarily have abstract methods.

24. What is the difference between Static Nested Class and Inner Class?
Answer: Static Nested Class is an inner class declared as static (static), which can be instantiated without depending on the outer class instance. And the usual inner class needs to be instantiated after the outer class is instantiated,'

25. Will there be memory leaks in Java? Please describe briefly.
Answer: In theory, Java will not have memory leak problems because of its garbage collection mechanism (GC) (this is also an important reason why Java is widely used in server-side programming); however, in actual development, there may be useless but reachable objects. Objects that cannot be reclaimed by GC will also leak memory. An example is that the objects in Hibernate's Session (first-level cache) are persistent, and the garbage collector will not recycle these objects, but there may be useless garbage objects in these objects.

26. Can an abstract method be static at the same time, can be a local method at the same time, and can be modified by synchronized at the same time?
Answer: Neither. Abstract methods need to be overridden by subclasses, while static methods cannot be overridden, so the two are contradictory. Native methods are methods implemented by native code (such as C code), while abstract methods are not implemented, which is also contradictory. Synchronized is related to the implementation details of the method, and abstract methods do not involve implementation details, so they are also contradictory.

27. What is the difference between static variables and instance variables?
Answer: A static variable is a variable modified by the static modifier, also known as a class variable. It belongs to a class and does not belong to any object of the class. No matter how many objects a class creates, there is only one copy of a static variable in memory. ; Instance variables must depend on an instance, you need to create an object and then access it through the object. Static variables allow multiple objects to share memory. In Java development, there are usually a large number of static members in context classes and utility classes.

28. Is it possible to issue a call to a non-static method from within a static method?
Answer: No, static methods can only access static members, because non-static method calls need to create objects first, so objects may not be initialized when calling static methods.

30. What is GC? Why have GC?
Answer: GC means garbage collection. Forgetting or wrong memory collection can lead to instability or even crash of the program or system. Java programmers don't have to worry about memory management because the garbage collector does it automatically.

31. String s=new String("xyz"); How many string objects are created?
Answer: Two objects, one is "xyz" in the static storage area, and the other is an object created on the heap with new.

32. Can an interface extend an interface? Can an abstract class implement an interface? Can an abstract class inherit a concrete class?
Answer: An interface can inherit an interface. Abstract classes can implement (implements) interfaces, and abstract classes can inherit concrete classes, but only if the concrete class must have a clear constructor.

33. Can a ".java" source file contain multiple classes (not inner classes)? What are the restrictions?
Answer: Yes, but a source file can only have at most one public class (public class) and the file name must be exactly the same as the class name of the public class.

34. Can Anonymous Inner Class inherit other classes? Is it possible to implement an interface?
Answer: You can inherit other classes or implement other interfaces. This method is commonly used in Swing programming to implement event monitoring and callbacks.

35. Can an inner class refer to members of its containing class (outer class)? Are there any restrictions?
Answer: An inner class object can access the members of the outer class object that created it, including private members.

36. What are the uses of the final keyword in Java?

Answer: (1) Modified class: Indicates that the class cannot be inherited; (2) Modified method: Indicates that the method cannot be overridden; (3) Modified variable: Indicates that a variable can only be assigned once and its value cannot be modified (constant).

38. Conversion between data types:
1) How to convert strings to basic data types?
2) How to convert basic data type to string?
Answer:
1) Call the method parseXXX(String) or valueOf(String) in the wrapper class corresponding to the basic data type to return the corresponding basic type;
2) One method is to connect the basic data type with an empty string ("") (+) to get the corresponding string; another method is to call the valueOf(…) method in the String class to return the corresponding string

40. How to convert GB2312 encoded string to ISO-8859-1 encoded string?
Answer: The code is as follows:
String s1 = "Hello";
String s2 = newString(s1.getBytes("GB2312"), "ISO-8859-1");

41. Date and time:
1) How to get the year, month, day, hour, minute and second?
Date date=new Date();
//Format java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(date);
System.out. println(time);

42. Print the current moment of yesterday.
Answer:
public class YesterdayCurrent {
public static void main(String[] args){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(cal.getTime()) ;
}
}

43. Compare Java and JavaSciprt.
Answer: JavaScript and Java are two different products developed by two companies. Java is an object-oriented programming language launched by the original Sun Company, which is especially suitable for the development of Internet applications; while JavaScript is a product of Netscape Company, developed to extend the functions of the Netscape browser, which can be embedded in Web pages. Object and event-driven interpreted language, its predecessor is LiveScript; and Java's predecessor is Oak language.
The following is a comparison of the similarities and differences between the two languages:
1) Object-based and object-oriented: Java is a real object-oriented language, and objects must be designed even to develop simple programs; JavaScript is a scripting language, which It can be used to make complex software that has nothing to do with the network and interacts with users. It is an Object-Based and Event-Driven programming language. Therefore, it provides a wealth of internal objects for designers to use;
2) Interpretation and compilation: The source code of Java must be compiled before execution; JavaScript is an interpreted programming language, and its source code does not need to be compiled. It is interpreted and executed by the browser;
3) Strongly typed variables and weakly typed variables: Java adopts strong type variable checking, that is, all variables must be declared before compilation; for variable declarations in JavaScript, its weak type is used. That is, the variable does not need to be declared before use, but the interpreter checks its data type at runtime;
4) The code format is different.
ADDED: The four points listed above were given in the original so-called standard answer. In fact, the most important difference between Java and JavaScript is that one is a static language and the other is a dynamic language. The current trends in programming languages ​​are functional languages ​​and dynamic languages. Classes are first-class citizens in Java, while functions are first-class citizens in JavaScript. For this kind of question, it is more reliable to answer in your own language during the interview.

45. What is the difference between Error and Exception?
Answer: Error represents system-level errors and exceptions that the program does not have to deal with. It is a serious problem when recovery is not impossible but difficult; for example, memory overflow, it is impossible to expect the program to be able to Handling such cases; Exception represents an exception that needs to be caught or needs to be handled by the program, and is a design or implementation issue; that is, it represents a situation that would never have happened if the program was functioning properly.

46. ​​If there is a return statement in try{}, will the code in finally{} following the try be executed, when will it be executed, before or after return?
Answer: It will be executed, after the method returns Executed before the caller.

47. How to handle exceptions in Java language, how to use the keywords: throws, throw, try, catch, finally?
Answer: Java handles exceptions through object-oriented methods, classifies various exceptions, and provides a good interface. In Java, each exception is an object, which is an instance of the Throwable class or its subclasses. When an exception occurs in a method, an exception object is thrown, and the object contains exception information. The method of calling this object can catch the exception and handle it. Exception handling in Java is implemented through five keywords: try, catch, throw, throws and finally. Under normal circumstances, try is used to execute a program. If an exception occurs, the system will throw an exception. At this time, you can catch it by its type, or finally (finally) by the default handler. to handle; try is used to specify a block of procedures that prevents all "exceptions"; the catch clause immediately follows the try block and is used to specify the type of "exception" you want to catch; the throw statement is used to explicitly throw an "exception" Exception"; throws is used to indicate various "exceptions" that a member function may throw; finally to ensure that a piece of code is executed no matter what "exception" occurs; a try statement can be written outside a member function call, Write another try statement inside this member function to protect other code. Whenever a try statement is encountered, the "exception" frame is placed on the stack until all try statements are completed. If the next try statement does not handle some "exception", the stack will unwind until a try statement that handles this "exception" is encountered.

48. What are the similarities and differences between runtime exceptions and checked exceptions?
Answer: Exceptions indicate abnormal states that may occur during the running of the program. Runtime exceptions indicate exceptions that may be encountered in the normal operation of the virtual machine. They are common operating errors, which usually do not occur as long as the program is designed without problems. Checked exceptions are related to the context in which the program runs. Even if the program is designed correctly, it may still be caused by problems in use.

49. List some of your common runtime exceptions?
Answer:
ArithmeticException (arithmetic exception)
ClassCastException (class conversion exception)
IllegalArgumentException (illegal parameter exception)
IndexOutOfBoundsException (table out of bounds exception)
NullPointerException (null pointer exception)
SecurityException (security exception)

50. The difference between final, finally, finalize?
Answer: final: The modifier (keyword) has three uses: If a class is declared final, it means that it can no longer derive new subclasses, that is, it cannot be inherited, so It and abstract are antonyms. Declaring variables as final ensures that they will not be changed during use. Variables declared as final must be given an initial value at the time of declaration, and can only be read and unmodified in subsequent references. Methods that are declared final can also only be used and cannot be overridden in subclasses. finally: usually placed after try...catch, the code block is always executed, which means that whether the program is executed normally or an exception occurs, the code here can be executed as long as the JVM is not closed, and the code to release external resources can be written in finally in the block. finalize: A method defined in the Object class. In Java, the finalize() method is allowed to do the necessary cleanup work before the garbage collector clears the object from memory. This method is called by the garbage collector when the object is destroyed. By overriding the finalize() method, you can clean up system resources or perform other cleanup work.

52. Are List, Set, and Map inherited from the Collection interface?
Answer: List and Set are, but Map is not. Map is a key-value pair mapping container, which is obviously different from List and Set, while Set stores scattered elements and does not allow duplicate elements (the same is true for sets in mathematics), List is a container of linear structure, suitable for numerical value Index to access elements.

54. What is the difference between Collections and Collections?
Answer: Collection is an interface, which is the parent interface of containers such as Set and List; Collections is a tool class that provides a series of static methods to assist container operations. These methods include container search, sorting, thread safety, etc. Wait.

55. When the three interfaces of List, Map and Set access elements, what are the characteristics of each?
Answer: List accesses elements at a specific index and can have duplicate elements. Set cannot store duplicate elements (use the object's equals() method to distinguish whether the elements are duplicates). Map saves the key-value pair mapping, and the mapping relationship can be one-to-one or many-to-one. Both Set and Map containers have two implementation versions based on hash storage and sorting tree. The theoretical access time complexity of the version based on hash storage is O(1), while the implementation based on sorting tree version can insert or delete elements when inserting or deleting elements. A sorting tree is formed according to the element or the key of the element to achieve the effect of sorting and deduplication.

57. Both the sleep() method of the Thread class and the wait() method of the object can suspend the execution of the thread. What is the difference between them?
Answer: The sleep() method (sleep) is a static method of the thread class (Thread). Call this method It will make the current thread suspend execution for the specified time, and give the execution opportunity (CPU) to other threads, but the lock of the object is still maintained, so it will automatically resume after the sleep time ends (the thread returns to the ready state, please refer to Question 66. thread state transition diagram). wait() is a method of the Object class. Calling the object's wait() method causes the current thread to give up the object's lock (the thread suspends execution) and enter the object's wait pool. Only the object's notify() method (or notifyAll) is called. () method) can wake up the thread in the waiting pool to enter the lock pool, and if the thread regains the lock of the object, it can enter the ready state.

60. Please name the methods related to thread synchronization and thread scheduling.
answer:

  • wait(): Puts a thread in a waiting (blocking) state and releases the lock on the object it holds;
  • sleep(): makes a running thread sleep, it is a static method, calling this method to handle InterruptedException exception;
  • notify(): Wake up a thread in a waiting state. Of course, when this method is called, it cannot exactly wake up a thread in a waiting state, but the JVM determines which thread to wake up, and it has nothing to do with priority;
  • notityAll(): Wake up all threads in the waiting state. This method does not give the lock of the object to all threads, but lets them compete. Only the thread that obtains the lock can enter the ready state;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324514058&siteId=291194637