2017 common 50-way Java Foundation Questions collation (with answer)

Source: Internet
Author: User
Tags finally block

1, scope public,private,protected, and the difference when not written

A : the difference is as follows:

2, Anonymous Inner Class (anonymous inner Class) can extends (inherit) other classes, whether you can implements (implement) interface (interface)

A : the anonymous inner class is an inner class that has no name. Other classes cannot be extends (inherited), but an inner class can be used as an interface and implemented by another inner class

3. The difference between Static Nested class and Inner class

Answer: Nested class (generally C + +), Inner class (usually Java's argument). The biggest difference between a Java inner class and a C + + nested class is whether it has an external reference. Note: the static inner Class (Inner Class) means that 1 creates an object of the static inner class, does not require an external class object, and 2 cannot access an external class object from an object of a static inner class

4, the difference between & and &&

A : & is a bitwise operator that represents the bitwise AND Operation,&& is a logical operator, which represents the logical and (and)

5. The difference between Collection and collections

Answer: Collection is the ancestor interface of the collection class, and the inheritance and his interface are mainly set and List.collections is a helper class for the collection class, he provides a series of static methods to implement the search, sort, thread-safe operation of various sets.

6. When to use Assert

A : assertion (assertion) is a common debugging method in software development, which is supported in many development languages. In the implementation, assertion is a statement in the program, which checks a Boolean expression, a correct program must ensure that the value of the Boolean expression is true, if the value is False, the program is already in an incorrect state, The system will give a warning or exit. In general, assertion is used to ensure the most basic and critical correctness of the program. Assertion inspection is usually turned on during development and testing. To improve performance, the assertion check is usually turned off after the software is released

7, String s = new string ("XYZ"), several string Object created

Answer: Two, one character object, one character object reference object

8, Math.Round (11.5) how much? Math.Round (-11.5) how much?

Answer: Math.Round (11.5) ==12; Math.Round ( -11.5) The ==-11;round method returns the longest integer closest to the parameter, and the parameter adds 1/2 to the floor

9, short S1 = 1; S1 = s1 + 1; what's wrong? Short S1 = 1; S1 + = 1; what's wrong?

Answer: short S1 = 1; S1 = s1 + 1; (S1+1 operation result is int type, need cast type) short S1 = 1; S1 + = 1; (can be compiled correctly)

10. Java has no goto answer: reserved Words in Java, are not used in Java now

11. Does the array have the length () method? String has no length () This method

A : the array does not have the length () method and has the length property. String has length () This method

12, the difference between overload and override. Whether the overloaded method can change the type of the return value

A : the overridden overriding and overloaded overloading of a method are different manifestations of Java polymorphism. Overriding overriding is a representation of polymorphism between a parent class and a subclass, and overloading overloading is a representation of polymorphism in a class. If you define a method in a subclass that has the same name and arguments as its parent class, we say that the method is overridden (overriding). When an object of a subclass uses this method, the definition in the subclass is called, and for it the definition in the parent class is "masked". If more than one method with the same name is defined in a class, they either have a different number of arguments or have different parameter types, which is called a method overload (overloading). The overloaded method is to change the type of the return value

13, set of elements can not be repeated, then what method to distinguish the repetition or not? Are you using = = or equals ()? What difference do they have?

Answer: The elements in the set cannot be duplicated, so use the iterator () method to distinguish between duplicates or not. Equals () is to interpret whether the two sets are equal equals () and = = methods Determine whether the reference value points to the same object Equals () is overwritten in the class so that when the contents and types of the two detached objects match, the truth is returned

14, give me one of your most common to the runtime exception

A : Common run-time exceptions include these arithmeticexception, Arraystoreexception, Bufferoverflowexception, Bufferunderflowexception, Cannotredoexception, Cannotundoexception, ClassCastException, CMMException, Concurrentmodificationexception, Domexception, Emptystackexception, IllegalArgumentException, Illegalmonitorstateexception, Illegalpathstateexception, IllegalStateException, Imagingopexception, Indexoutofboundsexception, MissingResourceException, Negativearraysizeexception, NoSuchElementException, NullPointerException, Profiledataexception, ProviderException, Rasterformatexception, SecurityException, SystemException, Undeclaredthrowableexception, Unmodifiablesetexception, unsupportedoperationexception

15. What is the difference between error and exception?

A : error indicates a serious problem in situations where recovery is not impossible but difficult. For example, memory overflow. It is impossible to expect the program to handle such a situation exception represents a design or implementation problem. In other words, it means that if the program is running normally, it never happens

16, List, Set, whether the map inherits from collection interface

Answer: List,set Yes, map is not

17. What is the difference between abstract class and interface?

A : A class that declares the existence of a method and does not implement it is called an abstract class, which is used to create a class that embodies some basic behavior, declares a method for that class, but does not implement the class in that class. An instance of the abstract class cannot be created. However, you can create a variable whose type is an abstract class that points to an instance of a specific subclass. Cannot have abstract constructors or abstract static methods. The subclasses of the abstract class provide implementations for all abstract methods in their parent class, otherwise they are also abstract classes. Instead, implement the method in the subclass. Other classes that know their behavior can implement these method interfaces (interface) in a class are variants of abstract classes. In an interface, all methods are abstract. Multiple inheritance can be obtained by implementing such an interface. All the methods in the interface are abstract, without a program body. An interface can only define static final member variables. The implementation of an interface is similar to a subclass, except that the implementation class cannot inherit the behavior from the interface definition. When a class implements a special interface, it defines the method (which is given by the program body) to all such interfaces. It can then invoke the interface's method on any object that implements the interface's class. Because of an abstract class, it allows you to use the interface name as the type of the reference variable. The usual dynamic binder will take effect. A reference can be converted to an interface type or converted from an interface type, and the instanceof operator can be used to determine whether an object's class implements an interface

18, the abstract method can be static at the same time, whether it can be native at the same time, whether it can be synchronized

Answer: neither can

19, interface can inherit interface? is an abstract class achievable (implements) interface? Whether an abstract class can inherit entity classes (concrete Class)

A : an interface can inherit an interface. Abstract classes can implement (implements) interfaces, whether an abstract class can inherit an entity class, but only if the entity class must have a definite constructor

20. Whether the constructor constructor can be override

A : The constructor constructor cannot be inherited, so overriding cannot be overridden, but can be overloaded overloading

21. Whether the string class can be inherited

Answer: The string class is the final class and cannot be inherited

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

A : will execute and execute before return

23, use the most efficient method to calculate 2 times 8 and so on a few

Answer: 2 << 3

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

Answer: No, there is the same hash code

25, when an object is passed as a parameter to a method, this method can change the properties of the object, and can return the changed results, whether this is a value or a reference to pass

A : the value is passed. The Java programming language has only value-passing 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 contents of the object can be changed in the called method, but the object's reference is never changed

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

Answer: witch (EXPR1), expr1 is an integer expression. So the arguments passed to the switch and case statements should be int, short, char, or byte. Long,string can't act on Swtich.

27. Differences between ArrayList and vectors, HashMap and Hashtable

A : ArrayList and vectors are mainly from two aspects. I. Synchronization: Vectors are thread-safe, that is, synchronous, and ArrayList are unsafe, not synchronous two. Data growth: When growth is needed, Vector By default growth of the original, and ArrayList is the original half HashMap and Hashtable mainly from three aspects. I. Historical reasons: Hashtable is based on the old dictionary class, HashMap is an implementation of the map interface introduced by Java 1.2 two. Synchronization: Hashtable is thread-safe, that is, it is synchronous, and HashMap is unsafe for the line program. , not synchronous three. Value: Only HashMap can let you use NULL as the key or value of an entry for a table

28. Can I store a Chinese character in char type?

A : can be defined as a Chinese, because in Java encoding in Unicode, a char accounted for 16 bytes, so put a Chinese is no problem

29. What is GC? Why do we have a GC

Answer: GC is the meaning of garbage collection (Gabage Collection), memory processing is where programmers are prone to problems, forgetting or wrong memory recycling can cause program or system instability or even crashes, The GC functionality provided by Java can automatically monitor whether an object exceeds the scope to achieve the purpose of automatically reclaiming memory, and the Java language does not provide a way to release the displayed operation of the allocated memory.

30 Float type float f=3.4 is correct?

Answer: not correct. Accuracy is inaccurate and should be cast with coercion type, as follows: float f= (float) 3.4

31. Introduce the collection FrameWork in Java (including how to write your own data structure)?

Answer: The Collection framework is as follows: collection├list│├linkedlist│├arraylist│└vector│ └stack└setmap├hashtable├hashmap└weakhashmapcollection is the most basic set interface, and a collection represents a set of object, The collection element (Elements) map provides a key-to-value mapping

32, abstract class and interface?

A : abstract classes and interfaces are all used for abstraction, but abstract classes (in Java) can have their own partial implementations, while interfaces are completely an identity (with multiple inheritance capabilities). The Java class implementation is instantiated by implementing the Java.io.Serializable Interface Collection framework to implement the comparable interface and Comparator interface.

33, the difference between string and StringBuffer.

Answer: The length of the string is immutable, and the length of the StringBuffer is variable. If you are frequently manipulating the contents of a string, especially if the content is to be modified, use StringBuffer, and if you need a string at the end, use the ToString () method of StringBuffer

34, talk about final, finally, finalize the difference

A : final-modifier (keyword) If a class is declared final, it means that it can no longer derive a new subclass and cannot be inherited as a parent class. Therefore, a class cannot be declared abstract and declared final. Declaring variables or methods as final ensures that they are not changed in use. A variable declared as final must be given an initial value at the time of declaration, and can only be read in subsequent references and cannot be modified. A method that is declared final can also be used only, and cannot be overloaded with finally-to provide a finally block to perform any cleanup operations when the exception is handled. If an exception is thrown, the matching catch clause executes and the control enters the finally block (if any) finalize-the method name. Java technology allows the use of the Finalize () method to do the necessary cleanup before the garbage collector clears objects from memory. This method is called by the garbage collector to this object when it determines that the object is not referenced. It is defined in the Object class, so all classes inherit it. Subclasses override the Finalize () method to organize system resources or perform other cleanup work. The Finalize () method is called on the object before the garbage collector deletes the object.

35. What are the aspects of object-oriented features

A : There are mainly the following four aspects: 1. Abstraction: Abstraction is the omission of aspects of a topic that are not relevant to the current goal, in order to pay more attention to the aspects related to the current goal. Abstractions do not intend to understand all of the problems, but simply select one part of them, temporarily without some detail. Abstract includes two aspects, one is the process abstraction, the other is the data abstraction. 2. Inheritance: Inheritance is a hierarchical model of a junction class and allows and encourages the reuse of classes, which provides a way to articulate commonalities. A new class of objects can be derived from existing classes, a process known as class inheritance. The new class inherits the attributes of the original class, which is called the derived class (subclass) of the original class, and the original class is called the base class of the new class (The parent Class). Derived classes can inherit methods and instance variables from their base classes, and classes can modify or add new methods to make them more suitable for special needs. 3. Encapsulation: Encapsulation is to surround the process and data, access to data only through the defined interface. Object-oriented computing begins with this basic concept that the real world can be portrayed as a series of fully autonomous, encapsulated objects that access other objects through a protected interface. 4. Polymorphism: Polymorphism means that objects of different classes are allowed to respond to the same message. Polymorphism consists of parameterized polymorphism and inclusion polymorphism. Polymorphism language has the advantage of flexibility, abstraction, behavior sharing and code sharing, which solves the problem of application function with the same name.

36. Is string the most basic data type?

A : the basic data types are byte, int, char, long, float, double, Boolean, and short. The Java.lang.String class is of the final type, so you cannot inherit the class or modify the class. In order to improve efficiency and save space, we should use the StringBuffer class

37. What is the difference between int and Integer

Answer: Java offers two different types: reference types and primitive types (or built-in types). int is the raw data type of Java, and integer is the wrapper class provided by Java for Int. Java provides a wrapper class for each primitive type. Primitive type encapsulation class, Booleanboolean,charcharacter,bytebyte,shortshort,intinteger,longlong,floatfloat, The behavior of doubledouble reference types and primitive types is completely different, and they have different semantics. Reference types and primitive types have different characteristics and usages, including: size and speed issues, which types of data structures are stored as the default values that are specified when reference types and primitive types are used as instance data for a class. The default value of the object reference instance variable is NULL, and the default value of the original type instance variable is related to their type

38. What are the similarities and differences between runtime anomalies and general anomalies

A : An exception indicates an unhealthy state that may occur during a program run, and a run-time exception that represents an exception that might be encountered in a virtual machine's usual operation is a common run error. The Java compiler requires the method to declare a non-runtime exception that might occur, but does not require that a runtime exception that is not caught to be thrown must be declared.

39, say Arraylist,vector, LinkedList storage performance and characteristics

Answer: Both ArrayList and vectors use arrays to store data, which is larger than the actual stored data in order to add and insert elements, both of which allow the element to be indexed directly by ordinal, but the insertion element involves memory operations such as array element movement, so the index data is fast and the data is inserted slowly. Vector because of the use of the Synchronized method (thread-safe), usually performance is worse than ArrayList, and LinkedList using a doubly linked list for storage, index data by ordinal need to be forward or backward traversal, but when inserting data only need to record the item before and after items can be , so the insertion speed is faster.

40. The difference between HashMap and Hashtable

Answer: HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation), they all complete the map interface, the main difference is that the HASHMAP allows null (NULL) key value (key), because of non-thread security, the efficiency may be higher than Hashtable. HashMap allows NULL to be used as a entry key or value, and Hashtable is not allowed. HashMap hashtable contains method removed, changed to Containsvalue and ContainsKey. Because the contains method is easy to cause misunderstanding. Hashtable inherits from the dictionary class, and HashMap is an implementation of the map interface introduced by Java1.2. The biggest difference is that the Hashtable method is synchronize, and HashMap is not, when multiple threads access Hashtable, they do not need to synchronize their methods, and HashMap must provide external synchronization. The Hash/rehash algorithms used by Hashtable and HashMap are probably the same, so there is no big difference in performance.

41. What is the difference between heap and stack?

A : the Stack is a linear collection, and its addition and deletion of elements should be done in the same paragraph. The stack is processed in a last-in, first-out manner. A heap is a constituent element of a stack

42, Java interface and C + + virtual class of the same and different places

A : since Java does not support multiple inheritance, it is possible for a class or object to use a method or property that is within several classes or objects, and the existing single inheritance mechanism cannot satisfy the requirement. The interface has more flexibility than inheritance because there is no implementation code in the interface. When a class implements an interface, the class implements all the methods and properties inside the interface, and the properties inside the interface are public static under the default state, and all methods are public by default. A class can implement multiple interfaces.

43. Simple principle and application of exception handling mechanism in Java

A : when a Java program violates Java's semantic rules, the Java virtual machine will represent the error that occurred as an exception. There are 2 cases of violating semantic rules. One is the semantic check built into the Java class library. For example, array subscript is out of bounds, indexoutofboundsexception is thrown, and NullPointerException is thrown when a null object is accessed. Another scenario is that Java allows programmers to extend this semantic check, and programmers can create their own exceptions and freely choose when to throw exceptions with the throw keyword. All exceptions are subclasses of java.lang.Thowable.

43, the advantages and principles of garbage collection. and consider 2 kinds of recycling mechanisms

Answer: A notable feature of the Java language is the introduction of a garbage collection mechanism, which makes it possible for the C + + programmer to solve the most troublesome memory management problems, which makes it unnecessary for Java programmers to consider memory management when writing programs. Because there is a garbage collection mechanism, objects in Java no longer have a "scope" concept, and only references to objects are scoped. Garbage collection can effectively prevent memory leaks and effectively use memory that can be used. The garbage collector is typically run as a separate low-level thread, unpredictable and clear and recyclable for 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 of an object or all objects. The recycling mechanism has generational replication garbage collection and token garbage collection, incremental garbage collection.

44. What are the collection classes you know? The Main method?

A : the most common collection classes are List and Map. The specific implementation of the list includes ArrayList and vectors, which are variable-sized lists that are more appropriate for building, storing, and manipulating any type of object. List is useful for cases where elements are accessed by numeric indexes. MAP provides a more general method of storing elements. The Map collection class is used to store element pairs (called "Keys" and "values"), where each key is mapped to a value.

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

Answer: The loading of classes in the JVM is implemented by ClassLoader and its subclasses, and Java ClassLoader is an important Java Runtime system component. It is responsible for locating and loading classes of class files at run time.

46. What are the various methods of sorting? Please list

A : Sort by: Insert sort (direct insert sort, hill sort), swap sort (bubble sort, quick sort), select sort (Direct select sort, heap sort), merge sort, assign sort (box sort, base sort) Quick sort pseudo code. //Use Quick Sort method for a[0:n-1] to sort from a[0:n-1] Select an element as M i d D l E, the element is the fulcrum to divide the remaining elements into two segments left and r i g H T, so that the elements in L E F t are equal to the fulcrum, and right The elements are greater than or equal to the fulcrum recursively use the quick Sort method to sort the left by recursively using the quick Sort method to sort right to the result of L E F t + m i d d l e + r i g h t

47, the Java language How to handle exception, keyword: throws,throw,try,catch,finally what is the meaning of each? Can I throw an exception in a try block?

Answer: Java uses an object-oriented approach to exception handling, classifies various exceptions, and provides a good interface. In Java, each exception is an object, which is an instance of the Throwable class or other subclass. When an exception is thrown, a method throws an exception object that contains the exception information, and the method that invokes the object can catch the exception and handle it. Java exception handling is achieved through 5 keywords: try, catch, throw, throws, and finally. In general, a try to execute a program, if an exception occurs, the system will throw (throws) an exception, when you can catch it by its type (catch), or finally (finally) by the default processor to handle. Use try to specify a piece of program that prevents all "exceptions". Immediately following the try program, you should include a catch clause to specify the type of "exception" you want to catch. The throw statement is used to explicitly throw an "exception". Throws is used to indicate the various "exceptions" that a member function might throw. Finally, a piece of code is executed to ensure that a piece of code occurs regardless of the "exception". You can write a try statement outside of a member function call and write another try statement inside this member function to protect the other code. Whenever a try statement is encountered, the "exception" frame is placed on the stack until all the try statements are completed. If the next-level try statement does not handle an "exception", the stack expands until it encounters a try statement that handles this "exception."

48. Can I include more than one class (not an inner class) in a ". Java" source file? What are the restrictions?

Answer: yes. Only one class name must be the same as the file name.

49. Are there several types of streams in Java? The JDK provides some abstract classes for inheritance for each type of stream, tell me what classes they are.

A : byte stream, character stream. The byte stream inherits from the InputStream OutputStream, and the character stream inherits from the InputStreamReader OutputStreamWriter. There are many other streams in the java.io package, mainly to improve performance and ease of use.

50. There is a memory leak in Java, please describe it briefly.

Answer: yes. Memory leaks can occur when you implement a heap-loaded data structure, see effective java.

51. What is the mechanism for polymorphism in Java?

A : the overridden overriding and overloaded overloading of a method are different manifestations of Java polymorphism. Overriding overriding is a representation of polymorphism between a parent class and a subclass, and overloading overloading is a representation of polymorphism in a class.

52. What is the basic principle of the garbage collector? Can the garbage collector reclaim memory right away? What is the way to proactively notify a virtual machine for garbage collection

A : for GC, when a programmer creates an object, the GC starts to monitor the address, size, and usage of the object. Typically, a GC uses a graph to record and manage all objects in the heap. In this way, you determine which objects are "accessible" and which objects are "unreachable." When the GC determines that some objects are unreachable, it is the responsibility of the GC to reclaim those memory spaces. OK. The programmer can manually execute System.GC () to notify the GC to run, but the Java language specification does not guarantee that the GC will execute.

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

Answer: static i = 10; Constant Class A; A.I =10;//Variable

54. What is Java serialization and how do I implement Java serialization?

A : serialization is a mechanism for dealing with the flow of objects, the so-called object flow, which is to stream the contents of an object. It is possible to read and write to a Fluidized object, or to transfer the streamed object between the networks. Serialization is a problem that is raised when reading and writing to an object stream. Serialization implementation: Implement the Serializable interface for the class that needs to be serialized, there is no method to implement it, implements serializable just to annotate that the object is serializable, and then use an output stream ( such as: FileOutputStream) to construct a ObjectOutputStream object, followed by the WriteObject (object obj) of the ObjectOutputStream object method to write out (that is, save its state) the object with the parameter obj, and the input stream to restore.

55. Is it possible to make a call to a non-static method from within a static method?

A : No, if it contains the object's method (), the object cannot be guaranteed to initialize.

56, when writing the Clone () method, usually have a line of code, what is it?

Answer: Clone has a default behavior, Super.clone (); He is responsible for generating the correct size of space and copying it bit by digit.

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

Answer: use break; Return method.

58, List, MAP, set three interfaces, access to elements, what are the characteristics of each?

Answer: Lists hold elements in a particular order, and can have repeating elements. Set cannot have duplicate elements, internal ordering. Map holds the Key-value value, and value can be multivalued.

59, say some of the commonly used classes, packages, interfaces, please give 5

A : common classes: BufferedReader bufferedwriter filereader filewirter String integer Common packages: Java.lang java.awt java.io Java.util java.sql Common interface: Remote List Map Document NodeList

A programmer learning platform to share with you, so that you accumulate experience in the practice of mastering the principle. The main direction is the Java engineer. If you want to get a high salary, want to break through the bottleneck, want to compete with others to gain advantage, want to get into bat but have worried about interview, can add my Java Learning Group: 669823128.

2017 common 50-way Java Foundation Questions collation (with answer)

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.