"Java seconds technology seconds kill interviewer" Javase common Face Question (ii)

Source: Internet
Author: User

Tag: Is the console representation of the Loop action Ace callback theory file

21. How do I jump out of the current multiple nested loops in Java?

A: Before the outermost loop, add a tag such as a, and then use break A; You can jump out of multiple loops. (Java supports tagged break and continue statements that are somewhat similar to goto statements in C and C + +, but like avoiding goto, avoid using tagged break and continue, because it doesn't make your program more elegant, Many times even have the opposite effect, so this grammar actually does not know better)

22. Can the constructor (constructor) be rewritten (override)?

A: The constructor cannot be inherited and therefore cannot be overridden, but can be overloaded.

23. Two object values are the same (x.equals (y) = = true), but can have different hash code, this sentence right?

A: No, if two objects x and y satisfy x.equals (y) = = True, their hash code (hash code) should be the same. Java for the Eqauls method and the Hashcode method are defined as:

(1) If two objects are the same (the Equals method returns True), then their hashcode values must be the same;

(2) If two objects have the same hashcode, they are not necessarily the same.

Of course, you may not have to do as required, but if you violate the above principles you will find that when using containers, the same objects can appear in the set set, while the efficiency of adding new elements is greatly reduced (for systems using hash storage, if the hash code conflicts frequently, the access performance will be drastically reduced).

Add: About Equals and Hashcode methods, many Java programs are known, but many people just know, in Joshua Bloch's masterpiece "Effective Java" (Many software companies, "effective Java", " Java Programming Ideas and refactoring: Improving existing code quality is the Java programmer must read books, if you have not seen, then quickly go to the Amazon to buy a copy of it is described in this way: first the Equals method must satisfy the reflexivity (x.equals (x) Must return True), symmetry (x.equals (Y) returns True when Y.equals (x) must also return true), transitivity (X.equals (y) and y.equals (z) all return True when X.equals (z) must also 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 to any non-null value x,x.equals (NULL) must return FALSE. The tips for achieving a high-quality Equals method include: 1. Use the = = operator to check if the parameter is a reference to this object; 2. Use the instanceof operator to check if the parameter is the correct type 3. For the key attributes in the class, check that the properties of the parameter's incoming object match; 4. After writing the Equals method, ask yourself if it satisfies symmetry, transitivity, consistency ; 5. When overriding equals, always rewrite hashcode;6. Do not replace an object object in the Equals method argument with another type, and do not forget the @override annotation when overriding.

24. Can I inherit the String class?

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

Add: Inheriting a string is itself a bad behavior, and the best way to reuse the string type is the association relationship (HAS-A) and the dependency (use-a) rather than the inheritance relationship (IS-A).

25. When an object is passed as a parameter to a method, this method can change the properties of the object and return the changed result, is it a value pass or a reference pass?

A: The value is passed. Method calls in the Java language only support value passing of parameters. When an object instance is passed as a parameter to a method, the value of the parameter is a reference to the object. The properties of an object can be changed during the call, but changes to the object reference do not affect the caller. In C + + and C #, you can change the value of an incoming parameter by passing a reference or transmitting a parameter. You can write code like the following in C #, but you can't do it in Java.

Namespace CS01 {

class Program {    public static void swap(ref int x, ref int y) {        int temp = x;        x = y;        y = temp;    }    public static void Main (string[] args) {        int a = 5, b = 10;        swap (ref a, ref b);        // a = 10, b = 5;        Console.WriteLine ("a = {0}, b = {1}", a, b);    }}

}

Description: There is no reference in Java is very inconvenient, this point in Java 8 is still not improved, it is so in Java code is written in a large number of wrapper class (will need to be modified by the method call to the reference in a wrapper class, Then passing the wrapper object into the method will only make the code bloated, especially for developers who are transitioning from C and C + + to Java programmers.

The difference between 26.String and StringBuilder, StringBuffer?

Answer: (1) string and StringBuffer, Stringbuider:

    ①String:是不可变字符序列;②StringBuffer、StringBuider:是可变字符序列;

The ③string overrides the Equals method and the Hashcode method, and StringBuffer does not overwrite the Equals method and the Hashcode method, so the problem occurs when the StringBuffer object is stored in the Java collection class.

(2) StringBuffer and Stringbuider:

 ①StringBuffer:是JDK1.0版本的,线程安全,效率低;②StringBuilder:是JDK1.5版本的,线程不安全,效率高;

③ If a string variable is defined within a method, this situation may only have one thread accessing it, and there is no unsafe factor, then use StringBuilder. If you want to define member variables within a class, and the instance objects of this class are used in a multithreaded environment, it is best to use StringBuffer.

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

A: 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 Runtime system component that is responsible for locating and loading classes in class files at run time.

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 reading the data in the class's. class file into memory, usually by creating a byte array to read into the. class file, and then produce a class object corresponding to the loaded class. When the load is complete, the class object is not yet complete, 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, including: 1) If the class has a direct parent class and the class has not been initialized, initialize the parent class first, and 2) Execute the initialization statements sequentially if there are initialization statements in the class.

Class loading is done by the ClassLoader, which includes the root loader (BootStrap), the extension loader (Extension), the system loader (systems), and the user-defined class loader (subclass Java.lang.ClassLoader). Starting with Java 2 (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's own bootstrap is the root loader, and the other loaders have only one parent class loader. The load of a class first requests that the parent ClassLoader be loaded, and the parent ClassLoader is not loaded 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:

Bootstrap: Generally implemented with native code, responsible for loading the JVM base Core class library (Rt.jar);

Extension: Loads the class library from the directory specified by the Java.ext.dirs system property, and its parent loader is bootstrap;

System: Also called the application ClassLoader, whose parent class is extension. It is the most widely used class loader. It is the default parent loader for the user-defined loader, which records the class from the environment variable classpath or the directory specified by the system attribute Java.class.path.

28. What are the similarities and differences between abstract classes and interfaces (interface)?

A: (1) member Characteristics:

① Construction Method: interface does not have, abstract class has;

② member variables: Only constants in the interface, constants in the abstract class, variables are available;

③ member methods: interfaces only abstract methods, abstract methods, non-abstract methods are available;

(2) Relationship characteristics:

① classes and classes: Only single inheritance, but can be multi-layered inheritance;

② class and interface: The realization of the relationship, can be single implementation, can also be more realized;

③ interface and interface: Inheritance relationship, can be single-inheritance, but also multiple inheritance;

(3) Design concept:

① interface is a simple factory design mode, like a relationship, the interface is defined by the extension of the inheritance system function;

③ abstract class is a template design pattern, is a relationship, abstract class is defined by the inheritance system of a total of xxx;

Is there a memory leak in 29.Java, please describe it briefly?

A: In theory, Java has no memory leaks due to garbage collection (GC) (which is an important reason why Java is widely used in server-side programming); However, in real-world development, there may be useless but accessible objects that cannot be recycled by GC and therefore can also cause memory leaks to occur. For example, the objects in Hibernate's session (first-level cache) are persistent, and the garbage collector does not reclaim those objects, but there may be useless garbage objects in them, which can cause memory leaks if you do not close (close) or empty (flush) The first-level cache in a timely manner.

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

Answer: No. Abstract methods require subclasses to rewrite, 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 are contradictory. Synchronized is related to the implementation details of the method, and the abstract method does not involve implementation details, and therefore is contradictory to each other.

31. Is it possible to make a call to a non-static (Non-static) method from within a static method?

A: No, static methods can only access static members, because calls to non-static methods create objects first, and when static methods are called, they may not be initialized.

What is 32.GC? Why do you have a GC?

A: GC is garbage collection meaning, Java provides the GC function can automatically monitor whether the object exceeds the scope to achieve the purpose of automatic recovery of memory, so as to effectively prevent memory leaks. To request garbage collection, you can call one of the following methods: System.GC () or Runtime.getruntime (). GC (), but the JVM can mask the displayed garbage collection calls.

33.String st = null and String st = "" Difference? string s = new string ("XYZ") creates several objects?

A: (1) String St = null indicates that a string object is declared with reference to STR, but there is no memory space allocated for it.

(2) String st = "" means that an empty string of length equal to 0 is created and memory space is allocated in memory.

(3) String st = new string ("XYZ"), indicating that two objects were created:

     ①堆内存中一个new String;     ②常量池中一个字符串。

34. Is the interface inheritable (extends) interface? is an abstract class achievable (implements) interface? Can abstract classes inherit concrete classes (concrete Class)?

A: Interfaces can inherit interfaces, and multiple inheritance is supported. Abstract classes can implement (implements) interfaces, and abstract classes can inherit concrete classes or they can inherit abstract classes.

35.Anonymous Inner Class (anonymous inner Class) can I 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 and Android development to implement event snooping and callbacks.

36. Can an inner class reference a member of its containing class (an outer Class)? Are there any restrictions?

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

What is the difference between 37.final, finally and finalized?

A: (1) Final: The final modified class, not be able to inherit; The final modified method cannot be overridden; the amount of fianl modification, as a constant, can only be assigned once;

(2) Finally: Exception handling, and try, catch in combination with, can be added without, used to execute some code that must be executed, such as releasing resources;

(3) A method in the Finalized:object class that defines some cleanup work to be done before the object is reclaimed by the garbage collector.

38. Conversions between data types?

A: (1) How do I convert a string to a basic data type?

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

(2) How do I convert a base data type to a string?

One method is to concatenate the base data type with an empty string ("") to get its corresponding string, and the other is to call the valueof () method in the string class to return the corresponding string

39. How to implement string reversal and substitution?

A: There are many ways to write your own implementation or you can use the methods in string or Stringbuffer/stringbuilder. One common interview topic is recursive implementation of string inversion, as shown in the following code:

public static String reverse(String originStr) {    if(originStr == null || originStr.length() <= 1)        return originStr;    return reverse(originStr.substring(1)) + originStr.charAt(0);}

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

A: The code looks like this:

String S1 = "Hello";

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

"Java seconds technology seconds kill interviewer" Javase common Face Question (ii)

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.