Java learning path-simple basic interview questions, java path-Questions
1. What are the features of object orientation?
A: The object-oriented features mainly include the following:
1) Abstraction: Abstraction refers to the process of summarizing the common features of a class of objects to construct classes, including data abstraction and Behavior Abstraction. Abstraction only focuses on the attributes and behaviors of objects, and does not focus on the details of these behaviors.
2) Inheritance: inheritance is the process of creating a new class from the inherited information of an existing class. The class that provides the Inheritance Information is called the parent class (superclass, base class); the class that obtains the Inheritance Information is called the subclass (derived class ).
3) Encapsulation: encapsulation is usually used to enclose processes and data. Data access can only be performed through the defined interface. The essence of object-oriented is to portray the real world as a series of completely autonomous and closed objects. The method we write in the class is an encapsulation of the implementation details; the class we write is the encapsulation of data and data operations. It can be said that encapsulation is to hide everything that can be hidden and only provide the simplest programming interface to the outside world (you can think about the difference between a general washing machine and a fully automatic washing machine, obviously the fully automated washing machine package is better, so it is easier to operate ).
4) polymorphism: allows different sub-types of objects to make different responses to the same message. Simply put, the same method is called with the same object reference, but different things are done. Polymorphism can be divided into polymorphism during compilation and Runtime polymorphism. The Runtime polymorphism can be interpreted as: When system A accesses the services provided by system B, system B provides A variety of services, but everything is transparent to system. Method overload implements polymorphism (also known as pre-binding) during compilation, while method override implements polymorphism (also known as post-binding) during runtime ).
2. What are the differences between the scope public, private, and protected?
A: The differences are as follows:
The current category of the scope is the same as that of the package subclass.
Public √
Protected √ ×
Default √ ××
Private √ ×××
If this parameter is left blank, the default value is used. By default, other classes in the same package are equivalent to public, and other classes in different packages are equivalent to private ). Protected (protected) is public to subclass, and private to classes that are not in the same package that have no parent-child relationship.
3. Is String the most basic data type?
A: No. There are only eight basic data types in Java: byte, short, int, long, float, double, char, and boolean. Apart from the basic type (primitivetype) and enumeration type (enumeration type ), the rest are reference types ).
4. Is float f = 3.4 correct?
A: incorrect. 3.4 is a double number. Assigning a double value to float is a type of down-casting, which causes loss of precision, therefore, float f = (float) 3.4 needs to be forcibly converted; or writeFloatf = 3.4F;.
5. Is there any error in short s1 = 1; s1 = s1 + 1? Short s1 = 1; s1 + = 1; is there a mistake?
A: For short s1 = 1; s1 = s1 + 1; because 1 is of the int type, the s1 + 1 operation result is also of the int type. The type must be forcibly converted before being assigned to the short type. Short s1 = 1; s1 + = 1; can be correctly compiled, because s1 + = 1; equivalent to s1 = (short) (s1 + 1 ); implicit forced type conversion exists.
6. Is there a goto in Java?
A: goto is a reserved word in Java, which is not used in the current Java version. (The appendix of The book "The Java Programming Language" compiled by James Gosling (father of Java) provides a list of Java keywords, including goto and const, however, these two keywords cannot be used at present, so in some places they are called reserved words. In fact, I personally do not agree with this statement, because programmers familiar with the C language know that, the words used in the system library are called reserved words)
7. What is the difference between int and Integer?
A: Java is an almost pure object-oriented programming language. However, for the convenience of programming, it is not the basic data type of objects, but to be able to treat these basic data types as object operations, java introduces the corresponding wrapper class for each basic data type. The int encapsulation class is Integer, and the automatic packing/unblocking mechanism is introduced from JDK1.5, so that the two can be converted to each other.
Java provides encapsulation classes for each original type:
Original Type: boolean, char, byte, short, int, long, float, double
Encapsulation type: Boolean, Character, Byte, Short, Integer, Long, Float, Double
8. What is the difference between & and?
A: & operators are used in two ways: (1) bitwise AND; (2) logical and. & Operators are short circuits and operations. The difference between logic and short-circuit is very huge, although both require that the Boolean values on both sides of the operator are true, and the value of the entire expression is true. & The reason for short-circuit computation is that if the value of the expression on the left is false, the expression on the right is directly short-circuited and no computation is performed. In many cases, we may need to use & instead of &. For example, when verifying a user's logon, the user name is determined not null and not a null string and should be written as: username! = Null &&! Username. equals (""), the order of the two cannot be exchanged, and the & operator cannot be used, because if the first condition is not true, the equals of the string cannot be compared. Otherwise, an NullPointerException occurs. Note: The same is true for the differences between logical or operator (|) and short circuit or operator (|.
9. Explain the usage of stacks, heap, and static storage areas in the memory.
A: Normally, we define a variable of the basic data type, an object reference, and the field storage of function calls all use the stack space in the memory; objects Created by using the new keyword and constructor are placed in the heap space. literal values in the program, such as 100, "hello", and constants, are stored in the static storage area. Stack space is the fastest but also very small. Usually a large number of objects are stored in the heap space. The entire memory, including the virtual memory on the hard disk, can be used as a heap space.
String str = new String ("hello ");
In the preceding statement, str is placed on the stack, and the string object created with new is placed on the stack, while the literal "hello" is placed in the static storage area.
In the latest JDK version, a technology called "Escape analysis" is used to place some partial objects on the stack to improve the operation performance of objects.
10. What is the value of Math. round (11.5? What is Math. round (-11.5) equal?
A: The Return Value of Math. round (11.5) is 12, and that of Math. round (-11.5) is-11. The principle of rounding is to add 0.5 to the parameter and then perform the following rounding.
11. Does swtich work on byte, long, and String?
A: In early JDK, in switch (expr), expr can be byte, short, char, or int. Java introduced the enumeration type (enum), expr can also be enumeration, from version 1.5, or String ). Long is not allowed.
12. Calculate 2x8 in the most efficient way?
Answer: 2 <3 (shifts three places to the left by multiplying the power of 2 ).
13. Does the array have the length () method? Does String have the length () method?
A: The array does not have the length () method. It has the length attribute. String has the length () method.
14. In Java, how does one jump out of the current multi-nested loop?
A: Add A mark such as A before the outermost loop, and then use break A. multiple loops can be exceeded. (In Java, the break and continue statements with labels are supported, which are similar to the goto statements in C and C ++, but just like avoiding using goto, avoid using break and continue with tags)
15. Can constructor be overwritten )?
A: The constructor cannot be inherited, so it cannot be overwritten, but can be overloaded.
16. The two objects have the same value (x. equals (y) = true), but different hash codes are available, right?
A: No. If the two objects x and y meet the requirements of x. equals (y) = true, their hash codes should be the same. Java specifies the eqauls method and hashCode method as follows: (1) if the two objects are the same (The equals method returns true), their hashCode values must be the same; (2) if the hashCode of the two objects is the same, they are not necessarily the same. Of course, you do not have to follow the requirements, but if you violate the above principles, you will find that the same object can appear in the Set when using the container, at the same time, the efficiency of adding new elements will be greatly reduced (for systems that use Hash Storage, frequent hash code conflicts will cause a sharp decline in access performance ).
17. Can I inherit the String class?
A: The String class is a final class and cannot be inherited. String inheritance is an incorrect behavior. The best way to reuse the String type is to associate rather than inherit.
18. when an object is passed as a parameter to a method, this method can change the attributes of this object and return the changed result, so is it a value transfer or a reference transfer?
A: value transfer. Java programming language only supports value passing parameters. When an object instance is passed as a parameter to a method, the parameter value is a reference to the object. The object content can be changed in the called method, but the object reference will never change. In C ++ and C #, you can pass a reference to change the value of the input parameter.
19. What are the differences between String, StringBuilder, and StringBuffer?
A: The Java platform provides two types of strings: String and StringBuffer/StringBuilder, which can store and operate strings. Here, String is a read-only String, which means that the content of the String referenced by String cannot be changed. The string objects represented by the StringBuffer and StringBuilder classes can be directly modified. StringBuilder is introduced in JDK 1.5. It is the same as the StringBuffer method. The difference is that it is used in a single-threaded environment because it is not modified by synchronized in all aspects, therefore, it is more efficient than StringBuffer.
20. Differences between Overload and Override. Can overload methods be differentiated based on the return type?
A: Both method overloading and rewriting implement polymorphism. The difference is that the former implements polymorphism at compilation, while the latter implements polymorphism at runtime. Overload occurs in a class. If a method with the same name has a different parameter list (different parameter types, different parameter numbers, or different parameters), it is considered as overload; rewriting occurs between the subclass and parent class. Rewriting requires that the rewrite method of the subclass has the same return type as the override method of the parent class, which is better accessed than the override method of the parent class, there cannot be more exceptions than the declaration of the parent class's override method (the Rishi replacement principle ). Overload does not have special requirements on the return type.
21. How does JVM load class files?
A: In JVM, class loading is implemented by ClassLoader and its subclass. The class loader in Java is an important system component during Java runtime, it searches for and loads classes in class files at runtime.
Supplement:
1. Due to the cross-platform nature of Java, the compiled Java source program is not an executable program, but one or more class files. When a Java program needs to use a class, JVM ensures that the class has been loaded, connected (verified, prepared, and parsed), and initialized. Class loading refers to reading data from the. class file of the Class into the memory. Generally, a byte array is created to read data into the. class file, and then a class object corresponding to the loaded Class is generated. After the Class object is loaded, the Class object is incomplete, so the Class is not available at this time. After the class is loaded, it enters the connection phase, which includes verification and preparation (allocating memory for static variables and setting the default initial values) and parsing (replacing symbol references with direct references) three steps. At last, JVM initializes the class, including: 1. If the class has a direct parent class and the class has not been initialized, initialize the parent class first; 2. If the class has an initialization statement, execute these initialization statements in sequence.
2. the class is loaded by the class loader. The class loaders include the root loader (BootStrap), the Extension loader (Extension), and the System loader (System) and user-defined class loaders (java. lang. classLoader subclass ). Since JDK 1.2, the class loading process adopts the parent delegation mechanism (PDM ). PDM better guarantees the security of the Java platform. In this mechanism, the Bootstrap provided by JVM is the root loader, and other loaders have only one parent loader. Class loading first requests the parent class loader to load. When the parent class loader is powerless, it is loaded by its subclass loader. JVM does not provide reference to Bootstrap to Java programs. The following describes several classloaders:
A) Bootstrap: It is generally implemented using local code and is responsible for loading the basic JVM core class library (rt. jar );
B) Extension: load the class library from the directory specified by the java. ext. dirs system attribute. Its Parent loader is Bootstrap;
C) System: it is also called the application Class Loader. Its parent class is Extension. It is the most widely used class loader. It records classes from the environment variable classpath or the directory specified by the system attribute java. class. path. It is the default parent loader of the User-Defined loader.
22. Can a Chinese character be stored in a char variable? Why?
A: The char type can store a Chinese character, because the encoding used in Java is Unicode (no specific encoding is selected, and the character numbers in the character set are directly used, this is the only unified method). A char type occupies 2 bytes (16 bit), so it is okay to put a Chinese character.
Supplement: Unicode indicates that the characters in the JVM have different manifestations inside and outside the JVM. Unicode is used inside the JVM, when the character is transferred from the JVM to the outside (for example, stored in the file system), encoding conversion is required. Therefore, Java contains byte streams and byte streams, as well as conversion streams between the byte stream and the word throttling, such as InputStreamReader and OutputStreamReader. These two classes are the adapter classes between the byte stream and the byte stream, it undertakes the task of encoding conversion.
23. What are the similarities and differences between abstract class and interface?
A: abstract classes and interfaces cannot be instantiated, but can be referenced by defining abstract classes and interface types. If a class inherits an abstract class or implements an interface, all the abstract methods must be implemented. 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 and abstract methods and specific methods. Interfaces cannot define constructors and all methods are abstract methods. Abstract class members can be private, default, protected, and public, while all interface members are public. Abstract classes can define member variables, while the member variables defined in interfaces are actually constants. Classes with abstract methods must be declared as abstract classes, and abstract classes do not need abstract methods.
24. What are the differences between Static Nested Class and Inner Class?
A: Static Nested Class is an internal Class declared as static. It can be instantiated without relying on external Class instances. In general, internal classes must be instantiated before they can be instantiated.
25. Is there any memory leakage in Java? Please briefly describe it.
A: theoretically, Java has a garbage collection mechanism (GC) to prevent memory leakage (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. These objects cannot be recycled by GC and Memory leakage may occur. One example is that the objects in the Hibernate Session (level-1 cache) are persistent, and the garbage collector will not recycle these objects. However, these objects may have useless junk objects.
26. can abstract (abstract) methods be both static, local (native), and synchronized?
A: No. Abstract methods must be overwritten by subclass, while static methods cannot be overwritten. Therefore, they are in conflict. Local methods are implemented by local code (such as C code), while abstract methods are not implemented, which is also contradictory. Synchronized is related to the Implementation Details of methods. abstract methods do not involve implementation details, so they are also contradictory.
27. What are the differences between static variables and instance variables?
A: static variables are also called class variables. They belong to a class and do not belong to any object of the class. No matter how many objects are created for a class, static variables have only one copy in the memory; instance variables must depend on an instance. You need to create an object and then access it through the object.
28. Can I call non-static (non-static) methods from inside a static (static) method?
A: No. The static method can only access static members. Because an object must be created before calling a non-static method, the object may not be initialized when the static method is called.
29. How to clone objects?
A: There are two methods:
1. Implement the Cloneable interface and override the clone () method in the Object class;
2. Implement the Serializable interface and achieve cloning through object serialization and deserialization.
30. What is GC? Why does GC exist?
A: GC indicates garbage collection. Memory Processing is a vulnerable issue for programmers. Memory collection may cause instability or even crashes of programs or systems, the GC function provided by Java can automatically monitor whether the object exceeded the scope to automatically recycle the memory. the Java language does not provide a display operation to release the allocated memory. Java Programmers don't have to worry about memory management, because the Garbage Collector automatically manages. To request garbage collection, you can call one of the following methods: System. gc () or Runtime. getRuntime (). gc ().
Garbage collection can effectively prevent memory leakage and effectively use available memory. The garbage collector is usually used as a separate low-priority thread to clear and recycle objects that have died or are not used in the memory heap for a long time, programmers cannot call the Garbage Collector to recycle an object or all objects in real time. The collection mechanism involves several methods, such as generational replication, marking, and incremental garbage collection.
Supplement: standard Java processes have both stacks and stacks. The stack saves the original local variables and the heap saves the objects to be created. The Java platform's basic algorithm for heap memory collection and reuse is called marking and clearing. However, Java has improved it by using "generational garbage collection ". This method will divide the heap memory into different areas with the Java object lifecycle. During the garbage collection process, the object may be moved to different areas:
2. Eden (Eden): This is the original region of the object and is the only region of most objects.
2. Survivor's Paradise: Objects survived from the Garden of Eden will be moved here.
2. Tenured: this is the home of an old enough surviving object. The Minor-GC process does not touch this place. When the young generation collection cannot put objects in the lifetime maintenance Park, a full collection (Major-GC) will be triggered, and compression may be involved here to free up enough space for large objects.
JVM parameters related to garbage collection:
²-Xms/-Xmx --- initial heap size/maximum heap size
²-Xmn --- size of the young generation in the heap
²-XX:-DisableExplicitGC --- so that System. gc () does not have any effect
²-XX: + PrintGCDetail --- print GC details
-XX: + PrintGCDateStamps --- print the GC operation Timestamp
31. String s = new String ("xyz"); how many String objects are created?
A: There are two objects, one is the "xyx" of the static storage area, and the other is the object created on the stack with the new.
32. CAN interfaces inherit (extends) interfaces? Can an abstract class implement the (implements) interface? Can an abstract class inherit a specific class (concrete class )?
A: The interface can inherit the interface. Abstract classes can be implemented (implements) interfaces. abstract classes can inherit object classes, provided that the object classes must have clear constructors.
33. Can a ". java" source file contain multiple classes (not internal classes )? What are the restrictions?
A: Yes, but a single source file can only have one public class, and the file name must be exactly the same as the class name of the public class.
34. Can Anonymous Inner Class (Anonymous internal Class) inherit other classes? Can I implement interfaces?
A: You can inherit other classes or implement other interfaces. This method is often used in swing programming.
35. Can an internal class reference its members in the class? Are there any restrictions?
A: members of an internal class object that can access the external class object that creates it include private members.
36. What are the usage of the final keyword in Java?
A: The class cannot be inherited. It is a top-level class.
37. Point out the running result of the following program:
Class {
Static {
System. out. print ("1 ");
}
Public (){
System. out. print ("2 ");
}
}
Class B extends {
Static {
System. out. print ("");
}
Public B (){
System. out. print ("B ");
}
}
Public class Hello {
Public static void main (String [] ars ){
A AB = new B ();
AB = new B ();
}
}
Answer: execution result: 1a2b2b. When creating an object, the constructor calls the following sequence: Initialize static members, call the parent class constructor, initialize non-static members, and call the constructor.
38. Conversion between data types:
1) how to convert a string to a basic data type?
2) how to convert the basic data type to a string?
A:
1) call the method parseXXX (String) or valueOf (String) in the packaging class corresponding to the basic data type to return the corresponding basic type;
2) one way is to connect the basic data type with the Null String ("") (+) to obtain the corresponding string; another method is to call valueOf (…) in the String class (...) Returns the corresponding string.
39. How to reverse and replace strings?
A: There are many methods. You can write and implement it yourself, or use the methods in String or StringBuffer/StringBuilder.
40. How to convert a GB2312 encoded string to a ISO-8859-1 encoded string?
A: The Code is as follows:
String s1 = "hello ";
String s2 = newString (s1.getBytes ("GB2312"), "ISO-8859-1 ");
41. Date and Time:
1) How do I obtain the values of year, month, day, hour, minute, and second?
2) how to get the number of milliseconds from 00:00:00 on January 1, January 1, 1970 to the present?
3) how to get the last day of a month?
4) how to format the date?
A: The procedure is as follows:
1) create a java. util. Calendar instance and call the get () method to pass in different parameters to obtain the values corresponding to the parameters.
2) The number of milliseconds can be obtained in the following methods:
Calendar. getInstance (). getTimeInMillis ();
System. currentTimeMillis ();
3) The sample code is as follows:
Calendartime = Calendar. getInstance ();
Time. getActualMaximum (Calendar. DAY_OF_MONTH );
4) use the format (Date) method in the java. text. DataFormat subclass (such as SimpleDateFormat class) to format the Date.
42. Print the current time of yesterday.
A:
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 javasrt RT.
A: JavaScript and Java are two different products developed by two companies. Java is an object-oriented programming language launched by SUN, which is especially suitable for Internet application development. JavaScript is a product of Netscape, an object-and event-driven explanatory language that can be embedded into Web pages to expand the functions of the Netscape Browser. Its predecessor is LiveScript; the predecessor of Java is the Oak language.
The similarities and differences between the two languages are compared as follows:
1) object-based and object-oriented: Java is a real object-oriented language. objects must be designed for simple programs. JavaScript is a scripting language, it can be used to create complex software that is irrelevant to the network and interacts with users. It is an Object-Based and Event-Driven programming language. Therefore, it provides a wide range 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 and is interpreted by the browser;
3) Strong-type variables and weak-type variables: Java checks strong-type variables, that is, all variables must be declared before compilation; in JavaScript, variable declarations use their weak types. That is, variables do not need to be declared before they are used, but the interpreter checks their data types at runtime;
4) The code format is different.
I personally think that the most important difference between Java and JavaScript is a static language and a dynamic language. The current development trend of programming languages is functional language and Dynamic Language. In Java, classes are first-class citizens, while functions in JavaScript are first-class citizens.
44. When should I use assert?
A: assertion is a common debugging method in software development. Many development languages support this mechanism. 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. In implementation, AssertionError is a statement containing a Boolean expression. When executing this statement, it is assumed that the expression is true. If the expression is calculated as false, the system reports an AssertionError.
Assertions are used for debugging purposes:
Assert (a> 0); // throws an AssertionError ifa <= 0
There are two types of assertions:
Assert Expression1;
Assert Expression1: Expression2;
Expression1 should always generate a Boolean value.
Expression2 can be any expression that generates a value. This value is used to generate a string message that displays more debugging information.
Assertions are disabled by default. To enable assertions during compilation, use the source 1.4 flag:
Javac-source 1.4 Test. java
To enable assertions at run time, you can use-enableassertions or-ea flag.
To disable assertions during running, use the-da or-disableassertions flag.
To enable assertions in the system class, use the-esa or-dsa tag. You can also enable or disable Assertion Based on the package. You can place assertions on any location that is not expected to arrive normally. Assertions can be used to verify parameters passed to private methods. However, assertions should not be used to verify the parameters passed to the public method, because public methods must check their parameters whether or not assertions are enabled. However, you can use assertions to test the post-condition either in a public method or in a non-public method. In addition, assertions should not change the state of the program in any way.
45. What is the difference between Error and Exception?
A: Error indicates system-level errors and exceptions that do not need to be processed by the program. It is a serious problem when recovery is not impossible but difficult. For example, memory overflow, it is impossible to expect the program to handle such a situation; Exception indicates the exceptions that need to be captured or processed by the program, which is a design or implementation problem; that is, it indicates that if the program runs normally, never happen.
46. If there is a return statement in try {}, will the code in finally {} following this try be executed? When will it be executed, before or after return?
A: Yes. It will be executed before return.
47. How to handle exceptions in Java, and how to use keywords: throws, throw, try, catch, and finally?
A: Java uses object-oriented methods to handle exceptions, classify various exceptions, and provide good interfaces. In Java, each exception is an object, which is an instance of the Throwable class or its subclass. When a method encounters an exception, an exception object is thrown. The object contains the exception information. The method that calls this object can capture the exception and handle it. Java exception handling is implemented through five keywords: try, catch, throw, throws, and finally. Generally, try is used to execute a program. If an exception occurs, the system throws an exception. In this case, you can catch it by its type, or finally (finally) is handled by the default processor; try is used to specify a program to prevent all "exceptions"; catch clauses follow the try block, it is used to specify the type of "exception" you want to capture; throw is used to explicitly throw an "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, you can write a try statement outside a member function call, write another try statement inside this member function to protect other code. Every time a try statement is encountered, the framework of "exception" is placed on the stack until all try statements are completed. If the try statement at the next level does not process a certain "exception", the stack will be opened until a try statement that handles this "exception" is encountered.
48. What are the similarities and differences between runtime exceptions and checked exceptions?
A: An exception indicates an abnormal state that may occur during the running of the program. An exception indicates an exception that may occur during common operations on the virtual machine. It is a common running error, as long as the program is designed with no problems, it usually does not happen. The checked exception is related to the context environment where the program runs. Even if the program design is correct, it may still be caused by usage problems. The Java compiler requires that the method declare to throw a possible check exception, but it does not require that an uncaptured runtime exception be thrown.
49. list some common runtime exceptions?
A:
ArithmeticException
ClassCastException
IllegalArgumentException
IndexOutOfBoundsException
NullPointerException
SecurityException
50. What are the differences between final, finally, and finalize?
A: final: modifier (keyword) has three usage methods: If a class is declared as final, it means that it cannot create new subclass, that is, it cannot be inherited, therefore, it is an antonym of abstract. Declaring variables as final ensures that they are not changed during use. variables declared as final must be given an initial value at the time of declaration, but can only be read and cannot be modified in future references. Methods declared as final can only be used, and cannot be overwritten in subclass. Finally: usually put in try... The subsequent construction of catch always executes code blocks, which means that the code can be executed no matter whether it is normal or abnormal, as long as the JVM is not closed, you can write the code for releasing external resources in the finally block. Finalize: method defined in the Object class. Java allows the use of the finalize () method to clear objects from the memory before the garbage collector. This method is called by the garbage collector when the object is destroyed. The finalize () method can be rewritten to organize system resources or perform other cleanup tasks.
--- Repost other websites for favorites and learning. If any copyright infringement or privacy is involved, please delete them in a private chat.