The most valuable 50-way Java face test is suitable for access to Java programmer _java

Source: Internet
Author: User
Tags exception handling finally block garbage collection goto hash shuffle static class java keywords


The following is a comprehensive revision of the original Java face test set and answers to the questions and answers, the original topic has a lot of repeated topics and worthless topics, there are a lot of reference to the answer is also wrong, the revised Java side Test set reference to the latest version of the JDK, removed the EJB 2.x and other useless content, supplemented the data structure and algorithm-related topics, classic interview programming questions, large-scale Web site technology architecture, operating systems, databases, software testing, design patterns, UML and other content, but also a lot of knowledge points for in-depth analysis, such as the design of the Hashcode method, garbage collection of heap and generation , Java new concurrent programming, nio.2 and so on, I believe that for the preparation of Java programmers must be beneficial.



Java Programmer's face test set (1-50)



First, the Java Foundation section



1. What are the aspects of object-oriented features?



A : the characteristics of object-oriented mainly include the following several aspects:



1 Abstract: Abstract is the process of summarizing the common characteristics of a class of objects, including data abstraction and behavior abstraction. Abstractions focus only on the attributes and behavior of objects and do not pay attention to the details of those actions.



2 Inheritance: inheritance is the process of creating new classes from inherited information from existing classes. Classes that provide inheritance information are called parent classes (superclass, base class), and classes that get inherited information are called subclasses (derived classes). Inheritance allows for a certain continuity in the changing software system, and inheritance is also an important means to encapsulate the variables in the program (if not understood, please read Dr. Shanhong's "Java and schema" or "design pattern refinement" in the section on Bridge mode).



3) Encapsulation: The encapsulation is generally considered to bind the data to the method of manipulating the data, and access to the data can only be achieved through the defined interface. The object-oriented nature is to portray the real world as a series of fully autonomous and closed objects. The method we write in the class is an encapsulation of the implementation details; We write a class that encapsulates data and data operations. It can be said that encapsulation is to hide everything can be hidden, only to the outside world to provide the simplest programming interface (can think of ordinary washing machine and fully automatic washing machine, the difference between the obvious automatic washing machine encapsulation better so the operation is simpler; the smart phone we're using is also packaged well enough, Because of a few buttons to get everything done).



4 polymorphism: polymorphism refers to allowing objects of different subtypes to respond differently to the same message. The simple thing is to call the same method with the same object reference but do something different. Polymorphism is divided into compile-time polymorphism and Run-time polymorphism. If the object's method is treated as an object to the outside service, then run-time polymorphism can be explained as: When a system accesses the services provided by B system, B system has a variety of ways to provide services, but everything is transparent to a system (like an electric razor is a system, its power supply is B system, b system can use battery power or alternating current, or even solar energy, a system will only pass the B-Class object to invoke the method of power supply, but do not know what the underlying implementation of the power supply system, what is the way to obtain the power. The method overload (overload) implements the compile-time polymorphism (also known as the forward binding), whereas the method override (override) implements Run-time polymorphism (also known as post-binding). Runtime polymorphism is the object of the most essence of things, to achieve polymorphism need to do two things: 1. Method overrides (the subclass inherits the parent class and overrides an existing or abstract method in the parent class); 2. Object styling (referencing a subtype object with a parent type reference so that the same reference invokes the same method to behave differently depending on the subclass object).



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



Answer: The difference is as follows:



Scopes are currently similar to buns other



Public√√√√



Protected√√√x



Default√√xx



Private√xxx



A member of a class does not write access adornments defaults to default. The default is equivalent to exposing (public) to other classes in the same package, or private to other classes that are not in the same package. A protected (protected) subclass is equivalent to public, and a class that does not have a parent-child relationship in the same package is equivalent to private.



3. Is String the most basic data type?



Answer: No. There are only 8 basic data types in Java: Byte, short, int, long, float, double, char, Boolean; In addition to the base type (primitive type) and the enumeration type (enumeration type), All that remains is the reference type (reference type).



4, float f=3.4; Is it correct?



A : not true. 3.4 is a double-precision number, which assigns a double to float (float) to a lower transition (down-casting, also known as narrowing) that causes a loss of precision and therefore requires a forced type conversion float F = (float) 3.4; or written as a float F =3.4f;



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



Answer: for short S1 = 1; S1 = s1 + 1; Since 1 is of type int, the result of the s1+1 operation is also int, which requires a cast type to be assigned to the short type. and short S1 = 1; S1 = 1 can be compiled correctly because s1+= 1 is equivalent to S1 = (short) (S1 + 1), which has implied coercion type conversions.



6, does Java have goto?



A :goto is a reserved word in Java and is not used in the current version of Java. (According to the appendix to the "The Java Programming Language" written by James Gosling (the father of Java), a list of Java keywords is given, including Goto and const, but these two are not currently available keywords. So some places call it a reserved word, but the word reserved is supposed to have a broader meaning, because programmers familiar with C know that a combination of words or words used in a System class library is considered a reserved word.



7. What is the difference between int and integer?



Answer: Java is a near-pure object-oriented programming language, but for programming convenience or introduction is not the object of the basic data types, but in order to be able to use these basic data types as Object operations, Java for each basic data types have introduced the corresponding wrapper type (wrapper class), int's wrapper class is integer, and the automatic boxing/unboxing mechanism is introduced from JDK 1.5 so that the two can be converted to each other.



Java provides a wrapper type for each original type:



Original type: boolean,char,byte,short,int,long,float,double



Packing Type: Boolean,character,byte,short,integer,long,float,double


Package Com.lovo; 
 Where do I ask hovertree.com public
class Autounboxingtest {public 
 
 static void Main (string[] args) { 
 Integer a = new Integer (3); 
 Integer B = 3;  Automatically boxing 3 into integer type 
 int c = 3; 
 System.out.println (A = = B); False two references do not refer to the same object 
 System.out.println (a = = c);//True a automatic unboxing to int type and C comparison 
 } 
} 


add: recently also encountered a face test, but also with automatic boxing and unboxing related, the code is as follows:


public class Test03 {public 
 
 static void Main (string[] args) {Integer f1 = m, f2 = m, F3 = +, F4 
 = 150;system.out.println (f1 = = F2); 
 System.out.println (F3 = = F4) 
 ; 
} 
Hovertree.com


It is easy to assume that both outputs are either true or False if they are unknown. The first thing to note is F1, F2, F3, F4 Four variables are integer objects, so the following = = operation is not compared to the value of the reference. What is the nature of boxing? When we assign an int value to an integer object, we call the static method of the integer class valueof, and if you look at the source code of the valueof, you know what's going on.


public static Integer valueof (int i) { 
 if (i >= integercache.low && i <= integercache.high) return 
  I Ntegercache.cache[i + (-integercache.low)]; 
 return new Integer (i); 
 } 
Hovertree.com


Integercache is the inner class of integer, and its code looks like this:


/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as R 
 Equired by JLS. * * The cache is initialized on the usage. 
 The size of the cache * May is controlled by the {@code-xx:autoboxcachemax=&lt;size&gt} option. * During VM initialization, Java.lang.Integer.IntegerCache.high property * May is set and saved in the private system PR 
 Operties in the * Sun.misc.VM class. 
 * hovertree.com * * private static class Integercache {static final int low =-128; 
 static final int high; 
 
 Static final Integer cache[]; 
  static {//high value May is configured by property int h = 127; 
  String Integercachehighpropvalue = Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); 
   if (integercachehighpropvalue!= null) {try {int i = parseint (Integercachehighpropvalue); 
   i = Math.max (i, 127); Maximum array size is integer.max_value h = math.min (i, Integer.max_value-(-low)-1); 
  The catch (NumberFormatException NFE) {//If The property cannot is parsed into an int, ignore it. 
 
  } high = h; 
  cache = new Integer[(high-low) + 1]; 
  int j = Low; 
 
  for (int k = 0; k &lt; cache.length; k++) cache[k] = new Integer (j + +); 
 range [ -128, 127] must be interned (JLS7 5.1.7) assert Integercache.high &gt;= 127; 

 Private Integercache () {}}


Simply put, if the literal value is between 128 and 127, then the new integer object will not be added, but the integer object in the constant pool is referenced directly, so the result of F1==F2 in the above interview question is true, and the F3==F4 result is false. The more seemingly simple face test of the more mystery, the need for the interviewer has a very deep skill.



8, the difference between & and &&?



A :the & operator has two uses: (1) bitwise and; (2) Logic and. The && operator is short-circuit and operation. The difference between the logic and the short circuit is very great, although both require that the Boolean value of the left and right sides of the operator is true the value of the entire expression is true. && is called a short-circuit operation because if the value of the expression on the left side of the && is false, the expression on the right will be shorted out directly, and no operation will be performed. Most of the time we may need to use && instead of, for example, when verifying that a user's name is not null and not an empty string when authenticating, it should be written as: username!= null &&!username.equals ("") , the order of the two can not be exchanged, not to use the & operator, because the first condition, if not set up, can not be a string of equals comparison, otherwise it will produce NullPointerException exception. Note: Logical OR operator (|) and short-circuit or operator (| | The same is true of the difference.



Add: If you are familiar with JavaScript, you may be more able to feel the power of short-circuit operation, want to become a master of JavaScript first from playing a short circuit operation start it.



9, explain the use of stack (stack), heap (heap) and static storage in memory.



A : usually we define a variable of the basic data type, a reference to an object, and a live save for a function call uses the stack space in memory, while objects created by the new keyword and constructor are placed in the heap space; the literal amount of the program (literal) is 100 as written directly. , "Hello" and constants are placed in a static storage area. Stack space operation is the fastest but also very small, usually a large number of objects are placed in the heap space, the entire memory including the hard disk of virtual memory can be used as a heap space to use.



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 the static store.



add: A newer version of Java uses a technique called escape analysis, where some local objects can be placed on the stack to enhance the object's operational performance.



10, Math.Round (11.5) equals how much? Math.Round (-11.5) equals how much?



Answer: The return value of Math.Round (11.5) is the return value of 12,math.round (-11.5) is-11. The principle of rounding is to add 0.5 to the parameter and then to the next rounding.



11, Swtich can function on the byte, whether it can function on a long, whether it can function on a string?



A : in the early JDK, switch (expr), expr can be byte, short, char, Int. Starting with version 1.5, the enumeration type (enum) is introduced in Java, and expr can be an enumeration, starting with JDK version 1.7, or a string. The long integer type is not allowed.



12, in the most efficient way to calculate 2 times 8?



A : 2 << 3 (3 digits to the left is equal to 3 times 2, and the right 3 is equal to 2 of 3).



Add: When we rewrite the Hashcode method for the class that we write, we may see the code shown below, but we don't quite understand why we should use such multiplication to produce hash code (hash code), and why this number is a prime, why do you usually choose the number 31? The answer to the first two questions you can Baidu, choose 31 because you can use the shift and subtraction operations to replace the multiplication, so that better performance. Speaking of which you may have thought: num <==> (num << 5)-Num, the left 5-bit equivalent multiplied by 2 of 5 times (32) and subtracting itself is the equivalent of multiplying by 31. Now the VM is able to automate this optimization.


Package Com.loonstudio; 
 public class PhoneNumber {private int areacode; 
 Private String prefix; 
 
 Private String linenumber; 
 @Override public int hashcode () {final int prime = 31; 
 int result = 1; 
 result = Prime * result + AreaCode; 
 result = Prime * result + ((linenumber = null)? 0:linenumber.hashcode ()); 
 result = Prime * result + ((prefix = null)? 0:prefix.hashcode ()); 
 return result; 
 @Override public boolean equals (Object obj) {if (this = obj) return true; 
 if (obj = null) return false; 
 if (GetClass ()!= Obj.getclass ()) return false; 
 PhoneNumber other = (phonenumber) obj; 
 if (AreaCode!= Other.areacode) return false; 
 if (linenumber = = null) {if (Other.linenumber!= null) return false; 
 else if (!linenumber.equals (Other.linenumber)) return false; 
 if (prefix = = null) {if (Other.prefix!= null) return false; 
 else if (!prefix.equals (Other.prefix)) return false; 
 return true; }}//Ask Hovertree.com
 


13. Is there a length () method for the array? Does String have a length () method?



A : the array has no length () method, and has a property of length. String has a length () method. In JavaScript, it is easy to confuse Java to get the length of a string that is obtained through the property of length.



14, in Java, how to jump out of the current multiple nested loops?



A : add a marker such as a to the outermost loop, then break a, and you can jump out of multiple loops. (It supports tagged break and continue statements in Java, which is a bit like a goto statement in C and C + +, but just like avoiding goto, you should avoid using tagged break and continue because it doesn't make your program more elegant, Many times even have the opposite effect, so this syntax actually does not know better)



15. Can the constructor (constructor) be overridden (override)?



A : The constructor cannot be inherited, so it cannot be overridden, but can be overloaded.



16, two object values are the same (x.equals (y) = = true), but can have different hash code, this sentence is correct?



A : No, if two objects x and y satisfy x.equals (y) = = True, their hash code (hash code) should be the same. Java provides for the Eqauls method and the Hashcode method: (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. Of course, you don't have to follow the instructions but if you violate the above principles, you will find that when you use a container, the same object can appear in the set set, while the efficiency of adding new elements is greatly reduced (for systems using hash storage, if frequent collisions of hash codes can result in a sharp drop in access performance).



Add: with regard to equals and Hashcode methods, many Java programs know, but many people just know, in Joshua Bloch's masterpiece "Effective Java" (Many software companies, "effective Java ", Java Programming ideas and refactoring: improving the quality of existing code is a Java programmer must read books, if you have not seen, then go to Amazon to buy a book this is the way to introduce the Equals method: First the Equals method must satisfy the reflexivity (x.equals (x) Must return True, symmetry (x.equals (Y) returns True, Y.equals (x) must return True), transitivity (X.equals (y) and y.equals (z) return true, X.equals (z) Also must return true) and consistency (when the object information referenced by x and Y is not modified, multiple calls to X.equals (y) should get the same return value), and a reference x,x.equals (null) for any non-null value must return FALSE. Tips for achieving a high quality Equals method include: 1. Use the = = operator to check whether the argument is a reference to this object; 2. Use the instanceof operator to check "whether the parameter is the correct type"; 3. For the key properties in the class, check that the parameters pass in the object's properties to match; 4. After writing the Equals method, ask yourself if it satisfies symmetry, transitivity, consistency, 5. You always override hashcode;6 when you override equals. Do not replace object objects in the Equals method arguments with other types, and do not forget @override annotations when overriding.



17. Can I inherit the String class?



Answer: The String class is the final class and cannot be inherited.



Add: Inheriting string is inherently a bad behavior, and the best way to reuse string types is to associate (HAS-A) rather than inherit (is-a).



18, when an object is passed as a parameter to a method, this method can change the object's properties, and can return the result of the change, then here is the value of the pass or reference pass?



A : It's value delivery. The Java programming language has only values that pass parameters. When an object instance is passed to a method as a parameter, the value of the parameter is a reference to that object. An object's properties can be changed during the call, but the object's reference will never change. In C + + and C #, you can change the value of an incoming parameter by passing a reference or transmitting a parameter.



Add: The fact that there is no reference in Java is very inconvenient, which is still not improved in Java 8, which is why there are a large number of wrapper classes in Java-written code (placing references that need to be modified by method invocation into a wrapper class). Passing the wrapper object into the method again will only make the code bloated, especially for developers who have transformed from C and C + + into Java programmers.



19, String and StringBuilder, stringbuffer the difference?



Answer: The Java platform provides two types of strings: string and Stringbuffer/stringbuilder, which can store and manipulate strings. Where string is a read-only string, it means that the string referenced by string cannot be changed. The string objects represented by the StringBuffer and StringBuilder classes can be modified directly. StringBuilder is introduced in JDK 1.5 and is identical to the StringBuffer method, except that it is used in a single-threaded environment because all aspects of it are not synchronized modified, So its efficiency is also slightly higher than the stringbuffer.



Add 1: There is a face question asked: Is there any case with + do string connection than call Stringbuffer/stringbuilder object Append method performance better? If the string obtained after the connection is already in the static storage area, then using the + to do string concatenation is superior to the Stringbuffer/stringbuilder append method.



Add 2: The following is also a face test, ask the output of the program to see if they can say the correct answer.


Package Com.lovo; 
 Where do I ask hovertree.com public
class Stringequaltest {public 
 
 static void Main (string[] args) { 
 String a = "progra Mming "; 
 String b = new String ("Programming"); 
 String C = "program" + "Ming"; 
  
 System.out.println (A = = B); 
 System.out.println (A = = c); 
 System.out.println (A.equals (b)); 
 System.out.println (A.equals (c)); 
 System.out.println (a.intern () = = B.intern ()); 
 } 
 


20, the difference between overloading (overload) and overriding (Override). Can overloaded methods be differentiated according to the return type?



A : the method of overloading and rewriting is the way to achieve polymorphism, the difference is that the former implementation of the compile-time polymorphism, and the latter implementation is run-time polymorphism. Overloads occur in a class with a method with the same name if there are different argument lists (parameter types are different, the number of parameters is different or both are considered overloaded; overrides occur between subclasses and parent classes, overriding requires that subclasses be overridden to have the same return type as the parent-overridden method, which is better accessed than the parent-class overridden method. You cannot declare more exceptions (the Richter substitution principle) than the parent class is overridden by the method. Overload has no special requirements for the return type.






21. Describe the principle mechanism of the JVM loading class file?



Answer: The loading of classes in the JVM is implemented by the class loader (ClassLoader) and its subclasses, and the ClassLoader in Java is an important Java Run-time system component that is responsible for locating and loading classes in class files at run time.



Add:



1, because of 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, the JVM ensures that the class has been loaded, connected (validated, prepared, parsed), and initialized. Class loading refers to the reading of data from the. class file of the class into memory, usually by creating a byte array to read the. class file and then generating the class object corresponding to the loaded class. When the load is complete, the class object is incomplete, so the classes are not available at this time. When a class is loaded, it enters the connection phase, which includes three steps for validating, preparing (allocating memory for static variables and setting default initial values) and parsing (replacing symbolic references with direct references). Finally, the JVM initializes the class, which includes: 1 initializes the parent class if the class has a direct parent class and the class has not been initialized, 2 if an initialization statement exists in the class, executes the initialization statements sequentially.



2. Class loading is done by ClassLoader, class loaders include: Root loader (BootStrap), extension loader (Extension), System loader (systems), and user-defined class loaders (Java.lang.ClassLoader subclasses). Starting with JDK 1.2, the class loading process takes the Father delegation mechanism (PDM). PDM better guarantees the security of the Java platform, in which the JVM brings its own bootstrap is the root loader, all the other loaders have and only one parent class loader. The load of a class first requests the parent class loader to load, and the parent loader does not load itself by its child ClassLoader. The JVM does not provide a reference to the bootstrap to the Java program. The following is a description of several class loaders:



a) Bootstrap: generally implemented in local code, responsible for loading JVM base Core class library (Rt.jar);



b) Extension: Loads the class library from the directory specified by the Java.ext.dirs system attribute, whose parent loader is bootstrap;



c) System: also called the Application class loader, whose parent class is extension. It is the most widely used class loader. It records the class from an environment variable classpath or a directory specified by the system attribute Java.class.path, which is the default parent loader of the user-defined loader.



22, char variable can be stored in a Chinese character?



A :the char type can store a Chinese character because the encoding used in Java is Unicode (no specific encoding is selected, the number of characters in the character set is directly used, which is the only way to unify), and a char type is 2 bytes (16bit), So it is no problem to put a Chinese.



add: Using Unicode means that characters have different representations inside and outside the JVM and are Unicode inside the JVM, and encoding conversion is required when the character is moved from within the JVM to the outside (for example, in a file system). So there are byte streams and stream of characters in Java, as well as conversion flows between character streams and stream of bytes, such as InputStreamReader and Outputstreamreader, which are the adapter classes between the byte stream and the character streams, and assume the task of encoding conversion. For C programmers, this encoding conversion is probably dependent on the characteristics of the Union (Consortium/Commons) shared memory.



23. What are the similarities and differences between abstract classes (abstracts Class) and Interfaces (interface)?



A : abstract classes and interfaces cannot be instantiated, but you can define references to abstract classes and interface types. A class still needs to be declared an abstract class if it inherits an abstract class or implements an interface that requires all of its abstract methods to be implemented. Interfaces are more abstract than abstract classes, because constructors can be defined in abstract classes, can have abstract methods and concrete methods, and constructors cannot be defined in interfaces, and the methods are all abstract methods. Members in an abstract class can be private, default, protected, public, and members of the interface are all public. A member variable can be defined in an abstract class, and the member variables defined in the interface are actually constants. Classes that have abstract methods must be declared as abstract classes, and abstract classes do not have to have abstract methods.



24, Static nested class (Static Nested Class) and the internal class (Inner Class) different?



Answer: The static Nested class is an inner class that is declared static (static) and can be instantiated without relying on an instance of an external class. The usual inner class needs to be instantiated after the external class is instantiated, and its syntax looks weird, as shown below.


Package Com.lovo; /** * Poker Class (a pair of poker) hovertree.com * */public class Poker {private static string[] Suites = {"Spade", "Red Peach", "Grass flower", " 
 Box "}; 
 
 private static int[] faces = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; 
 
 Private card[] cards; 
 /** * constructor */public Poker () {cards = new card[52]; for (int i = 0; i &lt; suites.length. i++) {for (int j = 0; J &lt; Faces.length; J +) {Cards[i * + j] = new Card ( 
  Suites[i], faces[j]);  
  }}/** * Shuffle (random order) */public void Shuffle () {for (int i = 0, len = cards.length; i &lt; Len; i++) { 
  int index = (int) (Math.random () * len); 
  Card temp = Cards[index]; 
  Cards[index] = cards[i]; 
 Cards[i] = temp; 
 }/** * Licensing * @param the location of the index * * * */Public cards Deal (int index) {return cards[index]; /** * Card Class (a poker) * [Inner class] * @author Shanhao * */public class Cards {private String suite;//color Private in T face; Points Public Card (String suite, int face) {this.suite = suite; 
 This.face = face; 
  @Override public String toString () {String facestr = ""; 
  Switch (face) {case 1:facestr = "A"; Case 11:facestr = "J"; 
  Break Case 12:facestr = "Q"; 
  Break Case 13:facestr = "K"; 
  Break 
  Default:facestr = string.valueof (face); 
 return suite + facestr;
 } 
 } 
}


Test class:


Package Com.lovo; 
 
Class Pokertest {public 
 
 static void Main (string[] args) { 
 Poker Poker = new Poker (); 
 Poker.shuffle (); 
 C2 = poker.new Card ("Hearts", 1); Create yourself a card 
  
 System.out.println (C1);//Shuffle after the first 
 System.out.println (C2);//Print: Hearts A}/// 
Q Hovertree.com


25, there will be memory leaks in Java, please describe briefly.



A : theoretically Java has a garbage collection mechanism (GC) that does not have a memory leak problem (which is one of the main reasons Java is widely used in server-side programming); However, in actual development, there may be useless but accessible objects, These objects cannot be reclaimed by GC and memory leaks can occur. One example is that objects in the Hibernate session (first-level caching) are persisted, and the garbage collector does not reclaim them, but there may be unwanted garbage objects in those objects. The following example also shows a memory leak in Java:


 package Com.lovo; 
Why ask hovertree.com import java.util.Arrays; 
 
Import java.util.EmptyStackException; 
 public class Mystack<t> {private t[] elements; 
 
 private int size = 0; 
 
 private static final int init_capacity = 16; 
 Public Mystack () {elements = (t[]) new object[init_capacity]; 
 public void push (T elem) {ensurecapacity (); 
 elements[size++] = Elem; 
 Public T Pop () {if (size = = 0) throw new emptystackexception (); 
 return elements[--size];  
 private void Ensurecapacity () {if (elements.length = = size) {elements = arrays.copyof (elements, 2 * size + 1); } 
 } 
}


The above code implements a stack (Advanced (FILO)) structure, at first glance there seems to be no obvious problem, it can even through the various unit tests you write. However, the Pop method has a memory leak problem, when we use Pop method pop-up stack objects, the object will not be treated as garbage collection, even if the program using the stack no longer refer to these objects, because the stack of the internal maintenance of these objects expired reference (obsolete reference). In languages that support garbage collection, memory leaks are hidden, and this memory leak is actually an unconscious object hold. If an object reference is unconsciously preserved, then the garbage collector does not process the object or other objects referenced by the object, even if there are only a few of them, which can cause a lot of objects to be excluded from garbage collection and thus have a significant performance impact. In extreme cases, disk paging (virtual memory exchange data between physical memory and hard disk) is raised, and even outofmemoryerror is caused.



26. Can the abstract method be static at the same time (static), can it be a local method (native), and be synchronized modified at the same time?



A : neither can. Abstract methods require subclass overrides, and static methods cannot be overridden, so they are contradictory. Local methods are methods implemented by local code (such as C code), and abstract methods are not implemented and contradictory. The synchronized is related to the implementation details of the method, and the abstract method does not involve implementation details and is therefore contradictory.



27. What is the difference between a static variable and an instance variable?



A : a static variable is a variable modified by the static modifier, also known as a class variable, which belongs to a class, does not belong to any object of the class, a class, no matter how many objects are created, the static variable has only one copy in memory, and the instance variable must be dependent on an instance. You need to create the object before you can access it through the object. Static variables enable multiple objects to share memory. In Java development, there are usually a large number of static members in context classes and tool classes.



28. Can I emit a call to a non-static (non-static) method from within a static (static) method?



A : No, static methods can only access static members, because a non-static method's invocation creates the object first, so it is possible that the object was not initialized when the static method was invoked.



29, how to achieve object cloning?



Answer: There are two ways:



1. Implement the Cloneable interface and rewrite the Clone () method in the object class;



2. Implementation of the Serializable interface, through the serialization of objects and deserialization of the implementation of cloning, you can achieve a real depth of cloning, the code is as follows.


Package Com.lovo; 
 
Import Java.io.ByteArrayInputStream; 
Import Java.io.ByteArrayOutputStream; 
Import Java.io.ObjectInputStream; 
Import Java.io.ObjectOutputStream; 
 
public class Myutil { 
 
 private myutil () { 
 throw new Assertionerror (); 
 } 
 
 public static <T> T clone (T obj) throws Exception { 
 Bytearrayoutputstream bout = new Bytearrayoutputstream ();objectoutputstream Oos = new ObjectOutputStream (bout); 
 Oos.writeobject (obj); 
 
 Bytearrayinputstream bin = new Bytearrayinputstream (Bout.tobytearray ()); 
 ObjectInputStream ois = new ObjectInputStream (bin); 
 Return (T) ois.readobject (); 
  
 Description: The Close method that invokes the Bytearrayinputstream or Bytearrayoutputstream object has no meaning 
 //These two memory-based streams can release resources as long as the garbage collector cleans up the object 
//How to ask Hovertree.com


Here is the test code:


Package Com.lovo; 
 
Import java.io.Serializable; /** * Human * @author Shanhao * */class Person implements Serializable {private static final long Serialversionuid = 
 
 -9102017020286042305l; private String name; name private int age; Age private car car; 
 Driver Public person (String name, int age, car car) {this.name = name; 
 This.age = age; 
 This.car = car; 
 Public String GetName () {return name; 
 public void SetName (String name) {this.name = name; 
 public int getage () {return age; 
 public void Setage (int age) {this.age = age; 
 Public Car Getcar () {return car; 
 public void Setcar (car car) {This.car = car; 
 @Override public String toString () {return ' person [name=] + name +, age= ' + Age + ', car= ' + car + '] '; }/** * @author Shanhao */class car implements Serializable {private static final long serialvers 
 
 Ionuid = -5713945027627603702l; Private String brand; brand private int maxspeed; 
 Top speed public car (String brand, int maxspeed) {this.brand = brand; 
 This.maxspeed = Maxspeed; 
 Public String Getbrand () {return brand; 
 } public void Setbrand (String brand) {This.brand = brand; 
 public int getmaxspeed () {return maxspeed; 
 The public void setmaxspeed (int maxspeed) {this.maxspeed = Maxspeed; 
 @Override public String toString () {return "car [brand=" + Brand + ", maxspeed=" + Maxspeed + "]"; }//How to ask Hovertree.com class Clonetest {public static void main (string[] args) {try {person p1 = new per 
  Son ("Hao LUO", New Car ("Benz", 300)); person P2 = Myutil.clone (p1); 
  Deep cloning P2.getcar (). Setbrand ("BYD"); Modify the cloned Person object P2 the brand attribute of the associated car object//Original Person object P1 The associated car will not be affected//because its associated car object was also cloned when the person object was cloned System.out.println (P1 
 ); 
 catch (Exception e) {e.printstacktrace ();
 } 
 } 
}


Note: cloning based on serialization and deserialization is not only a deep clone, but more importantly, by generic qualification, you can check that the object being cloned supports serialization, which is done by the compiler, not by throwing an exception at run time. This is a scheme that is significantly better than cloning objects using the Clone method of the object class.



30, what is GC? Why should there be a GC?



Answer: GC is the meaning of garbage collection, memory processing is a problem for programmers, forget or wrong memory recycling can cause the program or system instability or even crash, Java provides the GC function can automatically monitor the object beyond the scope to achieve the purpose of automatically reclaim memory, The Java language does not provide a display operation method that frees allocated memory. Java programmers do not have to worry about memory management because the garbage collector is automatically managed. To request garbage collection, you can call one of the following methods:System.GC () or Runtime.getruntime (). GC () , but the JVM can block the display of garbage collection calls.



Garbage collection can effectively prevent memory leaks and effectively use memory that can be used. The garbage collector is usually run as a single, low-priority thread and, in unpredictable cases, cleans and reclaims objects that have died in the heap or that have not been used for a long time, and the programmer cannot call the garbage collector in real time for garbage collection on an object or all objects. In the early days of Java, garbage collection was one of the biggest bright spots in Java, because server-side programming needed to be effective in preventing memory leaks, but now Java's garbage collection has become a subject of much criticism. Mobile Smart end users often feel that iOS's system has a better user experience than Android, and one of the deep reasons is the unpredictability of garbage collection in the Android system.



add: There are many kinds of garbage collection mechanism, including: Generational replication garbage collection, tag garbage collection, incremental garbage collection and so on. Standard Java processes include stacks and heaps. The stack holds the original local variable, and the heap holds the object to be created. The Java platform's basic algorithm for heap memory recycling and reuse is called tagging and scavenging, but Java has improved it with "generational garbage collection." This approach divides the heap memory into different areas with the Java object's lifecycle, and may move objects to different regions during garbage collection:



Eden: This is the area where the object was originally born, and for most objects, this is the only area in which they exist.
Survivor's Paradise (Survivor): The objects that survived from the Garden of Eden will be moved here.
Lifelong Care Garden (tenured): This is the home of the surviving object that is old enough. The Young Generation Collection (MINOR-GC) process is not going to touch this place. When the young generation collection can not put the object into the lifelong garden, it triggers a full collection (MAJOR-GC), there may also be involved in compression, so as to make enough space for large objects.



JVM parameters related to garbage collection:



-XMS/-xmx---Heap initial size/heap maximum size
The size of the young generation in the-xmn---heap
-XX:-DISABLEEXPLICITGC---let System.GC () not have any effect
-xx:+printgcdetail---print GC details
-xx:+printgcdatestamps---Print GC action time stamp



31, String S=new string ("xyz"), several string objects created?



A : two objects, one is the "xyz" of the static store, and one is the object created on the heap with new.



32, is the interface inheritable (extends) interface? Does an abstract class implement (implements) interfaces? Can an abstract class inherit a specific class (concrete Class)?



Answer: interfaces can inherit interfaces. Abstract classes can implement (implements) interfaces, and abstract classes can inherit specific classes, provided that a specific class must have a definite constructor.



33, a ". Java" source file can contain multiple classes (not internal classes)? What's the limit?



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 class name of the exposed class.



34. Anonymous Inner Class (anonymous inner Class) can inherit other classes? Is it possible to implement an interface?



A : You can inherit other classes or implement other interfaces, which are commonly used in swing programming to implement event sniffing and callbacks.



35. Can the inner class reference the members of its containing class (external class)? Are there any restrictions?



A : an internal class object can access members of the external class object that created it, including private members.



36, what is the use of the final keyword in Java?



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



37, the following procedures to indicate the operation results:


Class a{ 
 
 static{ 
 System.out.print ("1"); 
 } 
 
 Public A () { 
 System.out.print ("2"); 
 } 
} 
 
Class B extends a{ 
 
 static{ 
 System.out.print ("A"); 
 } 
 
 Public B () { 
 System.out.print ("B"); 
 } 
} 
 Where to ask Hovertree.com public
class hello{public 
 
 static void Main (string[] args) { 
 A ab = new B (); 
 AB = new B (); 
 } 
 
}


Answer: the result: 1a2b2b. The order in which constructors are invoked when an object is created is to initialize the static member, then invoke the parent class constructor, initialize the Non-static member, and finally invoke the self constructor.



38. Conversion between data types:



1 How do I convert a string to a basic data type?



2 How do I convert a basic data type to a string?



For:



1 Call the method Parsexxx (string) or valueof (string) in the wrapper class corresponding to the base data type to return the corresponding base type;



2 One method is to connect the basic data type with the empty string ("") to get its corresponding string, and another method is to call the valueof (...) in the string class. method returns the corresponding string



39, how to implement the string reversal and replacement?



A : There are many ways to write your own implementation, or you can use the methods in string or Stringbuffer/stringbuilder. A common interview question is to use recursion to reverse the string, as shown in the following code:


public static string reverse (string originstr) { 
 if (originstr = null | | originstr.length () <= 1) Return 
  origin STR; 
 return reverse (originstr.substring (1)) + originstr.charat (0); 
 } How to ask Hovertree.com


40. How to convert a GB2312 encoded string into a iso-8859-1 encoded string?



Answer: The code looks like this:


String S1 = "Hello";

String s2 = newstring (S1.getbytes ("GB2312"), "iso-8859-1");


41, date and time:



1 How to get the month, day, hour minutes seconds?



2 How do I get the number of milliseconds from January 1, 1970 0:0 0 seconds to now?



3 How to get the last day of a month?



4 How to format the date?



A : The Operation method is as follows:



1 Create a Java.util.Calendar instance and call its get () method to pass in different parameters to obtain the value of the parameter



2 The following methods are available for this number of milliseconds:


Calendar.getinstance (). Gettimeinmillis (); 
System.currenttimemillis (); 
How to ask Hovertree.com


3) The sample code is as follows:


Calendar time = Calendar.getinstance (); 
Time.getactualmaximum (calendar.day_of_month); 
How to ask Hovertree.com


4 Use the Format (date) method in Java.text.DataFormat subclasses (such as the SimpleDateFormat Class) to format dates.



42, print the current moment yesterday.



For:


public class Yesterdaycurrent {public 
 static void Main (string[] args) { 
 Calendar cal = Calendar.getinstance (); 
 Cal.add (Calendar.date,-1); 
 System.out.println (Cal.gettime ()); 
 } 
How to ask Hovertree.com


43, compare Java and javasciprt.



Answer: JavaScript and Java are the two different products developed by the two companies. Java is an object-oriented programming language launched by the original Sun company, and is especially suited for Internet application development, while JavaScript is a product of Netscape, An object-oriented and event-driven interpretive language that can be embedded in Web pages to extend the capabilities of Netscape's browser, formerly known as LiveScript, and Java as the predecessor of the Oak language.



The following compare the similarities and differences between the two languages as follows:



1 Object-oriented and object-oriented: Java is a real object-oriented language, even if the development of simple programs, must design objects; JavaScript is a scripting language that can be used to create complex software that is unrelated to the web and interacts with the user. It is an object-based (object-based) and event-driven (Event-driven) programming language. As a result, it provides a very rich internal object for designers to use;



2 Interpretation and compilation: Java source code in the implementation, must be compiled; JavaScript is an interpretative programming language, and its sources are not compiled and interpreted by browsers;



3 Strongly typed variables and type weak variables: Java uses strongly typed variables to check that all variables must be declared before compiling, and that variable declarations in JavaScript use their weak type. That is, the variable does not need to be declared before it is used, but the interpreter checks its data type at runtime;



4 code format is not the same.



add: The four points listed above are given in the original standard answer. In fact, the most important difference between Java and JavaScript is that one is a static language and one is a dynamic language. The development trend of current programming language is functional language and dynamic language. Class is a first-class citizen in Java, while in JavaScript functions (function) are first-class citizens. For this kind of question, in the interview or in their own language to answer will be more reliable.



44. When will you use assert?



A :assertion (assertion) is a common debugging method in software development, which is supported in many development languages. Generally speaking, assertion is used to guarantee the most basic and critical correctness of a program. Assertion checks are typically opened during development and testing. To improve performance, the assertion check is usually turned off after the software is released. In the implementation, the assertion is a statement that contains a Boolean expression, which is assumed to be true when the statement is executed, and if the expression evaluates to False, then the system reports a assertionerror.



Assertion for debugging purposes:



ASSERT (a > 0); Throws an assertionerror if a <= 0



Assertions can be of two forms:



Assert Expression1;



Assert Expression1:expression2;



Expression1 should always produce a Boolean value.



Expression2 can be any expression that yields a value, which is used to generate a string message that displays more debugging information.



Assertions are disabled by default, and to enable assertions at compile time, you use the source 1.4 flag:



Javac-source 1.4 Test.java



To enable assertions at run time, you can use-enableassertions or-ea tags.



To choose to disable assertions at run time, you can use-da or-disableassertions tags.



To enable assertions in a system class, you can use-esa or-DSA tags. You can also enable or disable assertions on a package basis. You can place assertions at any location that is expected to not be reached normally. Assertions can be used to validate parameters that are passed to a private method. However, assertions should not be used to validate parameters that are passed to the public method, because the public method must check its arguments, regardless of whether the assertion is enabled. However, you can test the post condition with assertions 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, Error and exception what is the difference?



Answer: Error indicates system-level errors and exceptions that the program does not have to deal with, which is a serious problem in situations where recovery is not impossible but difficult; for example, a memory overflow, it is impossible to expect a program to handle such a situation; Exception represents an exception that needs to be captured or required to be handled by a program ; that is, it means that if the program is working correctly, it will never happen.



add:in the 2005 Motorola interview asked such a question "If a process reports a stack overflow run-time error, what ' the most possible?" , giving four option A. lack of memory; B. Write on a invalid memory space; C. recursive function calling; D. Array index out of boundary. Java programs can also encounter Stackoverflowerror when running, this is a mistake can not recover, can only modify the code, the answer to the interview question is C. If you write recursion that does not converge quickly, you are likely to throw a stack overflow error, as follows:


Package Com.lovo; 
 
public class Stackoverflowerrortest {public 
 
 static void Main (string[] args) { 
 main (null); 
 } 
}//Why? Hovertree.com


So be sure to remember two points when writing a program recursively: 1. recursive formula; 2. The convergence condition (no longer recursion but backtracking).



46, try{} There is a return statement, then immediately after this try finally{in the code will not be executed, when executed, before return or after?



A : it executes before the method returns the caller. It is not good for Java to allow the return value to be changed in Finally, because if a finally code block exists, the return statement in the try does not immediately return the caller, but instead records the returned value until the finally code block is executed and then returns its value to the caller. Then, if you modify the return value in Finally, this can cause a lot of trouble to the program, in C # It's syntactically impossible to do such a thing.



47, how the Java language for exception handling, keywords: throws, throw, try, catch, finally how to use?



Answer: Java makes exception handling through object-oriented method, classifies different kinds of anomalies, and provides good interface. In Java, each exception is an object that is an instance of the Throwable class or its subclasses. When a method has an exception, an exception object is thrown, which contains exception information, and the method that invokes the object can catch the exception and process it. Java exception handling is done with 5 keywords: try, catch, throw, throws, and finally. Typically, a try is used to execute a program, and if an exception occurs, the system throws (throw) an exception, at which point you can catch it by its type, or finally (finally) by the default processor; Try to specify a program that prevents all "exceptions" The catch clause is immediately after the try block to specify the type of "exception" you want to catch, the throw statement is used to explicitly throw an "exception", and the throws is used to indicate a variety of "exceptions" that a member function may throw; finally to ensure that a piece of code is "abnormal" regardless are executed in a piece of code; You can write a try statement outside of a member function call, and write another try statement inside the member function to protect other code. Whenever a try statement is encountered, the "exception" frame is placed on the stack until all the try statements are complete. If a try statement at the next level does not handle an "exception", the stack expands until it encounters a try statement that handles this "exception".



48. What are the similarities and differences between runtime anomaly and inspected anomaly?



A : The exception indicates that the program may appear in the process of abnormal state, run-time exceptions to the virtual machine in the normal operation of the possible exception, is a common run error, as long as the program design is no problem usually does not occur. An exception is related to the context in which the program is running, even if the program is correct, and may still be caused by a problem that is being used. The Java compiler requires that a method must declare a possible exception to be thrown, but does not require that a runtime exception be declared that is not caught. Exceptions and inheritance are frequently abused objects in object-oriented programming, and the use of exceptions in God's effective Java provides the following guidelines:



Do not use exception handling for normal control flow (a well-designed API should not force its callers to work with exceptions for normal control flow)
Use a Run-time exception for programming errors when you are using the tested exception for a recoverable condition
Avoid unnecessary use of the detected exception (some state detection methods can be used to avoid the occurrence of anomalies)
Priority use of standard exceptions
The exception that is thrown by each method must have a document
Keep the atomic nature of the anomaly
Do not ignore caught exceptions in catch



49. List some of your common run-time exceptions?



For:



ArithmeticException (arithmetic anomaly)



ClassCastException (class conversion exception)



IllegalArgumentException (illegal parameter exception)



Indexoutofboundsexception (following table out of bounds exception)



NullPointerException (null-pointer exception)



SecurityException (Security Exception)



50, final, finally, finalize the difference?



A :final: modifiers (keywords) have three uses: If a class is declared final, it means that it cannot derive a new subclass, that is, it cannot be inherited, so it is the opposite of abstract. Declaring variables final can guarantee that they will not be changed in use, and that a variable declared final must be given an initial value at the time of declaration, and can only be read in future references. Methods that are declared final are also used only and cannot be overridden in subclasses. Finally: Usually the construction behind the Try...catch always executes a block of code, which means that the program, whether normal or abnormal, can be executed as long as the JVM is not closed, and the code that frees the external resource is written in the finally block. Finalize:object the method defined in the class, Java allows you to use the Finalize () method to do the necessary cleanup before the garbage collector clears the object out of memory. This method is invoked by the garbage collector when destroying objects, by overriding the Finalize () method to organize system resources or perform other cleanup work.



The above is the entire content of this article, I hope to participate in the Java interview help, but also hope that we support the cloud habitat community.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.