1. What are the features of object-oriented?
A: Object-oriented features mainly have the following aspects:
-
1) Abstraction: Abstraction is the process of constructing a class by summarizing the common characteristics of a class of objects, including data abstraction and behavior abstraction. Abstractions focus only 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 information from an existing class. Classes that provide inheritance information are called superclasses (superclasses, base classes); The class that gets the inheritance information is called a subclass (derived class). Inheritance gives some continuity to a changing software system, and is also an important means of encapsulating variable factors in the program (please read Dr. Yan Hong’s “Java and Patterns” or the section on bridge patterns in “Design Patterns Refinement” if you don’t understand).
-
3) Encapsulation: Encapsulation is generally considered to bind data to methods that manipulate it, and data can only be accessed through defined interfaces. The essence of object orientation is to represent the real world as a series of completely autonomous, closed objects. The methods we write in our classes encapsulate the implementation details; We write a class that encapsulates data and data operations. It can be said that encapsulation is to hide everything that can be hidden, providing only the simplest programming interface to the outside world (think of the difference between ordinary washing machine and automatic washing machine, automatic washing machine is obviously better packaging and therefore easier to operate; The smartphones we use today are packaged well enough to do everything with a few buttons.)
-
4) Polymorphism: Polymorphism refers to allowing objects of different subtypes to respond differently to the same message. Simply put, the same object reference calls the same method but does different things. Polymorphism is divided into compile-time polymorphism and run-time polymorphism. If an object’s methods are viewed as services that the object provides to the outside world, then runtime polymorphism can be interpreted as: When the service system to provide A system access B, B system has A variety of way of the services they offer, but everything is transparent for A system (like electric razor is A system, its power supply system is B, B system can use the batteries or use alternating current (ac), and even may be solar energy, A system will only by the method of class B object call power supply, But it is not known what the underlying implementation of the power supply system is or how it is powered). Method overload implements compile-time polymorphism (also known as pre-binding), while method override implements runtime polymorphism (also known as post-binding). Runtime polymorphism is the essence of object orientation, and to achieve polymorphism you need to do two things:
-
- Method rewriting (when a subclass inherits a parent class and overwrites an existing or abstract method in the parent class);
-
- Object styling (using a parent type reference to refer to a subtype object, so that the same reference calls the same method and behaves differently depending on the subtype object)
2, access modifiers, public, private, protected, and don’t write what is the difference between (the default)?
A: The differences are as follows:
Scope current class same as package subclasses other public √ √ √ √
Protected √ √ √ ×
Default √ √ × ×
Private √ × × ×
Class members default to default when they do not write access modifiers. The default is public for other classes in the same package and private for classes not in the same package. Protected is public for subclasses and private for classes that are not parent-child in the same package.
Is String the most basic data type?
Answer: No. There are only eight basic data types in Java: byte, short, int, long, float, double, char, Boolean. Except for primitive type and enumeration type, all the other types are reference types.
4, float f = 3.4; Is that correct?
Answer: Not true. 3.4 is a double. Assigning a double to a float is down casting and will result in a loss of precision. Therefore, a cast float f =(float)3.4 is required. Or float f = 3.4f; .
5, short s1 = 1; s1 = s1 + 1; Didn’t you? short s1 = 1; s1 += 1; Didn’t you?
Answer: for short s1 = 1; s1 = s1 + 1; Since 1 is an int, s1+1 is also an int and requires a cast to assign to short. Short s1 = 1; s1 += 1; It compiles correctly because s1+= 1; S1 = (short)(s1 + 1); There is an implicit cast.
Does Java have a Goto?
A: Goto is a reserved word in Java and is not used in the current version of Java. The appendix to The book “The Java Programming Language” by James Gosling gives a list of Java keywords, including goto and const, but these are not currently available. Therefore, some places call it reserved word, but the term reserved word should have a broader meaning, because programmers familiar with C know that words or combinations of words that have special meaning are regarded as reserved words.)
What is the difference between an int and an Integer?
A: Java is an almost pure object-oriented programming language. However, for the sake of programming convenience, it still introduces basic data types that are not objects. However, in order to treat these basic data types as objects, Java introduces a corresponding Wrapper class for each basic data type. The wrapper class for int is Integer, and since JDK 1.5 automatic boxing/unboxing has been introduced to make them interchangeable. Java provides a wrapper type for each primitive type: Boolean, char, byte, short, int, long, float, double Wrapper type: Boolean, Character, byte, short, Integer, long, float, double
Addendum: RECENTLY I encountered an interview question, which was also related to automatic packing and unpacking. The code is as follows:
It’s easy to assume that both outputs are either true or false if you don’t know what you’re doing. The first thing to note is that the variables f1, f2, f3, and F4 are all Integer objects, so the following == operation compares references rather than values. What is the nature of packing? When we assign an int value to an Integer object, valueOf, the static method of the Integer class, is called. If you look at valueOf’s source code, you can see what happens.
IntegerCache is the inner class of Integer, and its code looks like this:
To put it simply, if the literal value is between -128 and 127, then no new Integer object is created, but the Integer object in the constant pool is referenced directly, so f1==f2 is true and F3 ==f4 is false. The more seemingly simple the interview question, the more mystery, which requires the interviewer to have considerable skills.
8. The difference between & and &&?
Answer: The & operator can be used in two ways: (1) bitwise and; (2) Logic and. The && operator is the short-circuit and operation. The difference between logic and short-circuit and is huge, although both require booleans on the left and right sides of the operator to be true for the entire expression. Am& is called short-circuited because if the expression to the left of am& is false, the expression to the right will be short-circuited and not evaluated. In many cases, you might want to use ampersand instead of ampersand. For example, when verifying that the user’s login name is not null and not an empty string, you should write: username! = null &&! If the first condition is not true, then a NullPointerException will be generated. If the first condition is not true, then a NullPointerException will be generated. Note: the Boolean or operator (|) and short circuit or operator (| |) difference, too. Note: If you are familiar with JavaScript, you will probably feel the power of short-circuiting. If you want to become a JavaScript expert, start with short-circuiting.
Explain the use of stack, heap, and static storage areas in memory.
A: Usually we define a variable of a basic data type, a reference to an object, and the field storage of function calls all use the stack space in memory; Objects created by the new keyword and constructor are placed in the heap space; Literals in the program, such as the directly written 100, “hello,” and constants, are stored in static storage. Stack space is the fastest operation but also small, usually a large number of objects are placed in the heap space, the entire memory including virtual memory on the hard disk can be used as heap space. String STR = new String(” hello “); In the above statement, STR is placed on the stack, the string object created with new is placed on the heap, and the literal “hello” is placed in static storage. Bonus: Newer versions of Java use a technique called “escape analysis” to put local objects on the stack to improve their performance.
10. How much is math.round (11.5)? What is math.round (-11.5)?
Answer: Math.round(11.5) returns 12 and math.round (-11.5) returns -11. Rounding works by adding 0.5 to a parameter and rounding it down.
Can swtich work on byte, can swtich work on long, can swtich work on String
A: In the early JDK, in Switch (expr), expr could be byte, short, char, or int. Since version 1.5, The enumeration type (enum) has been introduced in Java. Expr can also be enumerations, and since JDK 1.7, it can also be strings. Long integers are not allowed.
12. Calculate 2 times 8 in the most efficient way possible.
Answer: 2 << 3 (moving three places to the left is the same as multiplying by two to the third, moving three places to the right is the same as dividing by two to the third). Add: when we rewrite the hashCode method for our class, we might see something like this. We don’t really understand why we use this multiplication to produce a hashCode, why this number is prime, and why the number 31 is usually chosen. You can do your own research on the answers to the first two questions, but choose 31 because you can use shifts and subtraction instead of multiplication for better performance. 31 * num <==> (num << 5) -num, moving five places to the left is the same as multiplying by two to the fifth power (32). Subtracting itself is the same as multiplying by 31. Today’s VMS can do this automatically.
Does array have a length() method? Does String have a length() method?
A: Arrays do not have a length() method, they have a length attribute. String has the length() method. In JavaScript, the length of a string is obtained through the length attribute, which is easily confused with Java.
14. How do I get out of the current multiple nested loops in Java?
A: Before the outermost loop, add A marker such as A, then use break A; You can jump out of multiple loops. (Java supports labeled break and continue statements, which act somewhat like GOto statements in C and C++, but just as goto is to be avoided, labeled break and continue statements should be avoided because they don’t make your program any more elegant, and in many cases have the opposite effect. So it’s actually better not to know.)
15. Can the constructor be overridden?
A: Constructors cannot be inherited and therefore cannot be overridden, but they can be overridden.
16. Two objects with the same value (x.equals(y) == true) can have different hash codes.
A: No, if two objects x and y satisfy x.equals(y) == true, they should have the same hash code. Java rules for the eqauls and hashCode methods :(1) if two objects are the same (the equals method returns true), their hashCode values must be the same; (2) If two objects have the same hashCode, they are not necessarily the same. And, of course, you may not want to do in accordance with the requirements, but if you are in violation of the principle of the above will have found in the use of the container, the same object can appear in the Set in the collection, and increase the efficiency of the new element will be dramatically reduced (for using hash storage system, if the hash code frequently conflict will cause the access performance fell sharply). Supplement: Many Java programs know about equals and hashCode methods, but many people just know about them. In Joshua Bloch’s book Effective Java, Java Programming Minds, and Refactoring: The equals method is described in Improving The Quality of Existing Code, a must-see book for Java programmers: The equals method must be reflexive (x.equials (x) must return true), symmetric (x.equials (y) must return true, and transitive (x.equials (y) and y.equials (z) must both return true). X.equials (z) must also return true) and consistency (multiple calls to x.equials (y) should return the same value when the object information referenced by x and y has not been modified), and x.equials (null) must return false for any reference to x that is not null. Tips for implementing high-quality equals methods include: 1. Use the == operator to check whether arguments are references to this object; 2. Use the instanceof operator to check whether the parameter is of the correct type. 3. For key attributes in the class, check whether the attributes of the object passed in the parameter match them; 4. After writing the equals method, ask yourself if it satisfies symmetry, transitivity, and consistency; Always rewrite hashCode when overriding equals; 6. Do not replace the Object in the equals method argument with another type, and do not forget the @override annotation when overriding.
17. Can I inherit the String class?
A: The String class is final and cannot be inherited. Add: Inheriting strings IS inherently A mistake, and the best way to reuse strings IS by association (HAS-a) rather than inheritance (IS-A).
18. When an object is passed as a parameter to a method that changes the object’s properties and returns the changed result, is it value passing or reference passing?
Answer: Value passing. The Java programming language only passes parameters by value. When an object instance is passed to a method as a parameter, the parameter’s value is a reference to that object. The properties of an object can be changed as it is called, but the reference to the object is never changed. C++ and C# can change the value of an argument passed in by passing a reference or passing out a parameter. Supplement: The inconvenience of not passing references in Java has not been improved in Java 8, which is why there are so many Wrapper classes in code written in Java (putting references that need to be modified through method calls into a Wrapper class and passing the Wrapper object into the method). This only leads to bloated code, especially for developers who have made the transition from C and C++ to Java programmers.
19. What is the difference between String and StringBuilder?
A: The Java platform provides two types of strings: String and StringBuffer/StringBuilder, which can store and manipulate strings. String is read-only, which means that the contents of the String referenced by String cannot be changed. The StringBuffer and StringBuilder classes represent string objects that can be modified directly. StringBuilder, introduced in JDK 1.5, is exactly the same method as StringBuffer, except that it is used in a single-threaded environment and is slightly more efficient than StringBuffer because all aspects of it are not modified by synchronized. Is there a situation where using + to concatenate strings is better than calling the Append method of a StringBuffer/StringBuilder object? String concatenation using + is superior to the Append method of StringBuffer/StringBuilder if the concatenated string already exists in static storage. Supplement 2: The following is also an interview question. Ask the output of the program to see if you can say the correct answer.
20. The difference between Overload and Override. Can overloaded methods be differentiated by return type?
Answer: Method overloading and overwriting are both ways of implementing polymorphism, the difference being that the former implements compile-time polymorphism, while the latter implements runtime polymorphism. Overloading occurs when a method with the same name has different argument lists (different parameter types, different number of arguments, or both) and is considered overloaded. Rewriting occurs between a subclass and its parent class. Rewriting requires that the subclass overridden method has the same return type as the parent overridden method, is more accessible than the parent overridden method, and cannot declare more exceptions than the parent overridden method (Richter’s substitution principle). Overloading has no special requirements for return types. Add: the question asked in huawei’s interview question is: why can’t overload be distinguished by return type? Tell us your answer!
21, Describe how the JVM loads class files.
A: The loading of classes in the JVM is done by the ClassLoader and its subclasses. The ClassLoader in Java is an important component of the Java runtime system that finds and loads classes in class files at run time. 1. Due to Java’s cross-platform nature, a compiled Java source program is not an executable program, but one or more class files. When a Java program needs to use a class, the JVM ensures that the class has been loaded, wired (validated, prepared, and parsed), and initialized. Loading a class refers to reading the data from the class’s.class file into memory, usually by creating a byte array that reads into the.class file and generates a class object corresponding to the loaded class. After loading, the Class object is not complete, so the Class is not available at this point. When the class is loaded, it enters the connect phase, which consists of three steps: validation, preparation (allocating memory for static variables and setting default initial values), and parsing (replacing symbolic references with direct references). Finally, the JVM initializes the class, including: 1 if the class has a direct parent and the parent has not been initialized, then initialize the parent first; 2 If there are initialization statements in the class, execute them in turn. 2. The loading of classes is accomplished by class loaders, including BootStrap, Extension, System and user-defined class loaders (a subclass of java.lang.classloader). Since JDK 1.2, the class loading process has adopted the parent delegate mechanism (PDM). PDM ensures the security of the Java platform. In this mechanism, the Bootstrap of the JVM is the root loader, while all other loaders have one or only one parent class loader. The loading of a class is first requested by the parent class loader, and only when the parent class loader is unable to do so is the subclass loader loaded by itself. The JVM does not provide a reference to Bootstrap to a Java program. A)Bootstrap: generally implemented in native code, is responsible for loading the JVM’s basic core libraries (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: also called application class loader, its parent class is Extension. It is the most widely used class loader. It records classes from the directory specified by the environment variable CLASspath or the system property java.class.path and is the default parent of a user-defined loader.
22, Can a char variable store a Chinese character? Why is that?
A: The char type can store a Chinese character, because the encoding used in Java is Unicode (the only way to be uniform). A CHAR type is 2 bytes (16 bits), so a Chinese character is ok. Note: Using Unicode means that characters have different representations inside and outside the JVM, both inside and outside the JVM as Unicode, and encoding conversions are required when the character is transferred from inside the JVM to outside (such as into a file system). So there are byte streams and character streams in Java, and conversion streams that convert between character streams and character streams, such as InputStreamReader and OutputStreamReader, which are the adapter classes between byte streams and character streams that do the encoding conversion; For C programmers, such coding transformations may depend on the union shared memory feature.
23. What are the similarities and differences between abstract classes and interfaces?
A: Neither abstract classes nor interfaces can be instantiated, but references to abstract classes and interface types can be defined. A class that inherits an abstract class or implements an interface must implement all of its abstract methods. Otherwise, the class still needs to be declared as abstract. An interface is more abstract than an abstract class, because an abstract class can define constructors, can have abstract methods and concrete methods, whereas an interface cannot define constructors and its methods are all abstract methods. Members in an abstract class can be private, default, protected, or public, while members in an interface are all public. Member variables can be defined in an abstract class, whereas member variables defined in an interface are actually constants. Classes with abstract methods must be declared as abstract classes, and abstract classes need not have abstract methods.
The difference between a Static Nested Class and an Inner Class?
A: Static Nested classes are internal classes that are declared Static and can be instantiated independent of external Class instances. The normal inner class needs to be instantiated by the outer class, and the syntax looks weird, as shown below.
Is there a memory leak in Java? Please describe it briefly.
A: Java is theoretically free of memory leaks because of its garbage collection (GC) mechanism (which is one of the reasons Java is so widely used for server-side programming); In real development, however, there may be useless but reachable objects that cannot be collected by the GC and can leak memory. An example is Hibernate Session (level 1 cache) objects that are persistent and are not collected by the garbage collector, but may contain garbage objects that are not useful. The following example also shows a memory leak in Java:
The code above implements a stack (FILO) structure that doesn’t seem to have any obvious problems at first glance, and it can even pass the various unit tests you write. The pop method, however, has a memory leak problem. When we pop an object from the stack, the object is not garbage collected, even if the application that uses the stack no longer references the object, because the stack maintains out-of-date references to the object. In languages that support garbage collection, memory leaks are hidden and are essentially unconscious object retention. If an object reference is inadvertently retained, the garbage collector does not process that object or any other object referenced by that object. Even if there are only a few objects, this can result in many objects being excluded from the garbage collection, which can have a significant impact on performance. In extreme cases, Disk Paging (exchanging data between physical memory and virtual memory of hard disks) can be triggered, or even cause outofMemoryErrors.
26. Can an abstract method be static, native, and synchronized?
A: Neither. Abstract methods need to be subclassed, while static methods cannot be overridden, so the two are contradictory. Local methods are methods implemented by native code (such as C code), whereas abstract methods are unimplemented and contradictory. Synchronized is concerned with the implementation details of a method; abstract methods are not concerned with implementation details and are therefore contradictory.
What is the difference between a static variable and an instance variable?
A static variable is a variable that is modified by a 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, a static variable has only one copy in memory. Instance variables must be dependent on an instance, and the object must be created and then accessed through the object. Static variables allow multiple objects to share memory. In Java development, context classes and utility classes typically have a large number of static members.
28. Can calls to non-static methods be made from inside a static method?
A: No, static methods can only access static members, because a call to a non-static method creates the object first, so the object may not be initialized when a static method is called.
29, how to implement object cloning?
A: There are two ways: 1. Implement Cloneable and override the Clone () method in Object; 2. Implement Serializable interface, clone through object serialization and deserialization, you can realize the real deep clone, the code is as follows.
Note: based on the realization of serialization and deserialization cloning is not only a deep, more important is through the generic limit, you can check out whether the Object supports serialization to clone, the inspection is done by the compiler, not throw an exception at run time, this is the solution using the Object class is obviously better than the method of clone cloned objects.
What is GC? Why GC?
A: GC means garbage collection, and memory processing is the place where programmers are prone to problems. Forgetting or wrong memory collection will lead to instability or even crash of the program or system. The GC function provided by Java can automatically monitor whether the object is out of scope so as to achieve the purpose of automatic memory collection. The Java language does not provide a display operation to free allocated memory. Java programmers don’t have to worry about memory management because the garbage collector manages it automatically. To request garbage collection, one of the following methods can be called: System.gc() or Runtime.geTruntime ().gc(), but the JVM can mask the garbage collection calls displayed. Garbage collection can effectively prevent memory leaks and efficiently use available memory. The garbage collector is typically run as a single, low-priority thread that unpredictably cleans and reclaims dead or unused objects in the heap. Programmers cannot call the garbage collector in real time to collect an object or all objects. In the early days of Java, garbage collection was one of the biggest highlights of Java, because server-side programming was required to effectively prevent memory leaks. However, time has changed, and Java’s garbage collection mechanism has become a thing of the past. Mobile intelligent terminal users generally feel that iOS system has a better user experience than Android system. One of the deep reasons lies in the unpredictability of garbage collection in Android system. Add-on: There are many garbage collection mechanisms, including generation copy garbage collection, tag garbage collection, incremental garbage collection, and so on. Standard Java processes have both stacks and heaps. The stack holds primitive local variables and the heap holds objects to be created. The Java platform’s basic algorithm for collecting and reusing heap memory is called mark and sweep, but Java improves on this with “generational garbage collection.” This approach divides the heap memory into different regions according to the life cycle of Java objects, and objects may be moved to different regions during garbage collection: • Eden: This is the region where objects were originally born, and for most objects, this is the only region they have ever existed. • Survivor Paradise: Survivors from the Garden of Eden are moved here. • Tenured: This is where surviving subjects who are old enough will go. The minor-GC process does not touch this area. A full collection (maj-GC) is triggered when the younger generation can’t fit objects into a lifetime retirement park, which may also involve compression to make room for large objects. JVM parameters related to garbage collection: • -xMS / -xmx — — Initial size of the heap/maximum size of the heap • -XMN — size of the young generation in the heap • -xx: -disableEXPLicitGC — Make system.gc () do nothing • • -xx :+PrintGCDetail — Prints the GC details • -xx :+PrintGCDateStamps — prints the GC operation timestamp
31, String s=new String(” xyz “); How many string objects are created?
A: Two objects, “XYZ” in static storage and an object created on the heap with new.
32. Does an interface extend an interface? Does an abstract class implement an interface? Can an abstract class inherit a Concrete class?
A: Interfaces can inherit from interfaces. An abstract class implements an interface, and an abstract class inherits a concrete class, but only if the concrete class has an explicit constructor.
Can a.java source file contain multiple classes (not inner classes)? What are the restrictions?
A: Yes, but there can be at most one public class in a source file and the file name must be exactly the same as the public class name.
Can Anonymous Inner classes inherit from other classes? Can interfaces be implemented?
A: You can inherit from other classes or implement other interfaces, which is common in Swing programming for event listening and callbacks.
35. Can an inner class reference a member of its containing class? Are there any restrictions?
A: An inner class object can access the members of the outer class object that created it, including private members.
What are the uses of the final keyword in Java?
A: (1) Modify class: indicates that the class cannot be inherited; (2) modification method: indicates that the method cannot be overwritten; (3) Modified variable: indicates that the value of a variable can only be assigned once and cannot be modified (constant).
37, Indicate the result of the following program:
A: Execution result: 1a2B2B. Object constructors are called in the order of initializing static members, then calling the parent class constructor, then initializing non-static members, and finally calling its own constructor.
Conversion between data types:
1) How to convert strings to primitive data types? 2) How to convert a primitive data type to a string? Answer: 1) Call 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 concatenate a primitive data type with an empty string (” “) to obtain its corresponding string; Another way is to call valueOf(…) in the String class. Method returns the corresponding string
39, how to achieve string inversion and replacement?
A: There are many methods. You can write your own implementation or use methods in String or StringBuffer/StringBuilder. A common interview question is to recursively invert a string, as shown below:
40. How to convert GB2312 encoded string to ISO-8859-1 encoded string?
A: The code looks like this: String s1 = “hello “; String s2 = newString(s1.getBytes(“GB2312”), “ISO-8859-1”);
41. Date and Time:
1) How to obtain the year, month, day, hour, minute, second? 2) How do I get the number of milliseconds from 00:00:00:00 on January 1, 1970 to the present day? 3) How to get the last day of a month? 4) How to format dates? A: The operation is as follows: 1) Create java.util.calendar instance and call its get() method to pass in a different parameter to get the corresponding value of the parameter. 2) Obtain the number of milliseconds in either of the following methods:
3) The sample code is as follows:
4) Use the format(Date) method in a subclass of Java.text. DataFormat (such as SimpleDateFormat) to format the Date.
Print the current moment of yesterday.
A:
Compare Java with JavaSciprt.
A: JavaScript and Java are two different products developed by two companies. Java is the original Sun company launched object-oriented programming language, especially suitable for Internet application development; JavaScript is the product of Netscape corporation. It is a kind of object – and event-driven interpretive language that can be embedded in Web pages to extend the function of Netscape browser. Java’s predecessor is the Oak language. The similarities and differences between the two languages are as follows: 1) Object-based and object-oriented: Java is a real object-oriented language, even to develop simple programs, you must design objects; JavaScript is a scripting language that can be used to create complex software that interacts with users independently of the web. It is an object-based and event-driven programming language. Thus it itself provides a very rich internal object for designers to use; 2) Interpretation and compilation: Java source code must be compiled before execution; JavaScript is an interpreted programming language. Its source code is interpreted and executed by the browser without compilation. 3) Strongly typed variables and weakly typed variables: Java uses strongly typed variable checking, that is, all variables must be declared before compilation; In JavaScript, variable declarations are weakly typed. That is, variables are not declared before they are used, but their data types are checked at run time by the interpreter. 4) Different code formats. Add: The four points listed above were originally given in the so-called standard answer. The most important difference between Java and JavaScript is that one is a static language and the other is a dynamic language. At present, the development trend of programming language is functional language and dynamic language. Classes are first-class citizens in Java, whereas functions are first-class citizens in JavaScript. It’s better to answer these questions in your own words during the interview.
44, When to use assert?
A: Assertion is a common method of debugging in software development, and is supported in many development languages. In general, assertion is used to ensure the most basic, critical correctness of the procedure. Assertion checking is usually turned on during development and testing. Assertion checking is usually turned off after software is released to improve performance. In implementation, an assertion is a statement containing a Boolean expression that is assumed to be true when executed; If the expression evaluates to false, an AssertionError is reported. Assertions are used for debugging purposes: Assert (a > 0); // throws an AssertionError if a <= 0 Assertions can take two forms: assert Expression1; assert Expression1 : Expression2 ; Expression1 should always produce a Boolean value. Expression2 can be an arbitrary expression that yields a value; This value is used to generate string messages that show more debugging information. Assertions are disabled by default and to enableassertions at compile time use the source 1.4 tag: javac -source 1.4 test.java to enableassertions at run time use the -enableassertions or -ea tag. To choose to disableassertions at run time, use the -da or -disableassertions tag. To enable assertions in a system class, use the -esa or -dSA flag. Assertions can also be enabled or disabled on a package basis. Assertions can be placed at any location that would not normally be expected to arrive. Assertions can be used to validate arguments passed to private methods. However, assertions should not be used to validate arguments passed to public methods, because public methods must check their arguments regardless of whether assertions are enabled. However, you can use assertions to test postconditions in both public and non-public methods. 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 represents system-level errors and exceptions that the program does not have to handle, and is a serious problem in cases where recovery is not impossible but difficult; You can’t expect your program to handle an overflow of memory, for example; Exception is an Exception that needs to be caught or handled by a program. It is a design or implementation problem. That is, it represents a situation that would never happen if the program worked properly. Supplement: MOTOROLA once asked such a question in an interview in 2005: “If a process reports a stack overflow run-time error, what’s the most possible cause?” A. lack of memory; b. write on an invalid memory space; c. recursive function calling; C. Array index out of boundary. A StackOverflowError may occur when the Java program is running. If you write a recursion that does not converge quickly, it is likely to cause a stack overflow error, as shown below:
So there are two things to keep in mind when writing recursively: 1. 2. Convergence conditions (when is it no longer recursive but backtracking).
46. Will the code in finally{} immediately following the try be executed and when, before or after the return?
A: It does, before the method returns to the caller. The way Java allows you to change a return value in finally is bad, because if there is a finally block, the return statement in the try does not return the caller immediately. Instead, it records the return value and returns it to the caller after the finally block is finished executing. Then, if you change the return value in finally, this will cause a lot of trouble for your program, which is syntactically forbidden in C#.
Java language how to handle exceptions, keywords: throws, throw, try, catch, finally respectively how to use?
A: Java takes an object-oriented approach to exception handling, classifying different exceptions and providing a good interface. In Java, each exception is an object that is an instance of the Throwable class or a subclass of it. When an exception occurs in a method, an exception object is thrown. The object contains the exception information, which can be caught and handled by the method calling the object. Java exception handling is implemented with five keywords: try, Catch, throw, throw, and finally. If an exception occurs, the system throws an exception. You can catch it by its type, or finally handle it by the default handler. Try is used to specify a piece of the program that prevents all “exceptions”; The catch clause follows the try block and specifies the type of “exception” you want to catch; The throw statement is used to explicitly throw an “exception”; Throws identifies the “exceptions” that a member function may throw. Finally to ensure that a piece of code is executed no matter what “exception” happens; You can write a try statement outside a member function call and another try statement inside the member function to protect other code. Each time a try statement is encountered, the “exception” frame is placed on the stack until all tries are complete. If the next level of try does not handle an “exception,” the stack expands until it encounters a try statement that does.
What are the similarities and differences between runtime anomalies and checked anomalies?
A: An exception is an abnormal state that may occur during the running of a program. A runtime exception is an exception that may occur during the common operation of a VM. It is a common operation error that will not occur as long as the program is designed without any problems. Checked exceptions are related to the context in which the program is running. Even if the program is designed correctly, it can still be caused by problems in use. The Java compiler requires methods to declare to throw checked exceptions that can occur, but not run-time exceptions that are not caught. Exceptions, like inheritance, are often overused in object-oriented programming, and Effective Java provides the following guidelines for their use: • Do not use exception handling for normal control flow (a well-designed API should not force its callers to use exceptions for normal control flow) • Use checked exceptions for situations that can be recovered, Use runtime exceptions for programming errors • Avoid unnecessary checked exceptions (exceptions can be avoided by some means of state checking) • Use standard exceptions in preference • Document exceptions thrown by each method • Keep exceptions atomic • Do not ignore caught exceptions in a catch
49, List some of your common runtime exceptions.
A: ClassCastException ArithmeticException (arithmetic exception) (class) IllegalArgumentException IndexOutOfBoundsException illegal parameters (abnormal) NullPointerException SecurityException
50, Final, finally, finalize?
A: Final: The modifier (keyword) can be used in three ways: If a class is declared final, it means that it cannot be subclassed, that is, it cannot be inherited, so it is the opposite of abstract. Declaring variables final guarantees that they will not be changed in use. Variables declared final must be given an initial value at the time of declaration and can only be read in future references. Methods declared final are also available only and cannot be overridden in subclasses. Finally: Usually placed in try… The catch construct always executes a code block, which means that the program executes normally or if an exception occurs. The code here will execute as long as the JVM is not shut down. Finalize: A method defined in the Object class that allows Java to use the Finalize () method to do the necessary cleanup before the garbage collector clears objects from memory. This method is called by the garbage collector when objects are destroyed, and can be used to clean up system resources or do other cleanup work by overriding finalize().
Collect data from a platform