Java interview questions-Basics

Source: Internet
Author: User
Tags finally block


Java basics:
1. the scope is public, private, and protected.
A: The differences are as follows:
Scope: current class, same package, Child class, other package
Public √
Protected √ ×
Friendly √ ××
Private √ ×××
The default value is friendly when no data is written.
2. Can anonymous inner class (anonymous internal class) be extends (inherited) other classes or implements (implemented) interface (Interface)
A: anonymous internal classes are internal classes without names. It cannot be extends (inherited) other classes, but an internal class can be used as an interface and implemented by another internal class
3. Differences between static nested class and inner class
A: Nested class (generally C ++) and inner class (generally Java ). The biggest difference between Java internal classes and C ++ Nested classes is whether there are external references. Note: The static internal class (inner class) means that 1 creates an object of the static internal class and does not need an external class object, 2. You cannot access an external class object from an object of a static internal class.
4. Differences between & and &
A: "&" indicates bitwise AND operation, and "&" indicates logical and (and)
5. Differences between collection and collections
A: collection is the upper-level interface of the Collection class. Its Inheritance interfaces mainly include set and list.
Collections is a help class for collection classes. It provides a series of static methods for searching, sorting, thread security, and other operations on various sets.
6. When to use assert?
A: assertion is a common debugging method in software development. Many development languages support this mechanism. In implementation, assertion is a statement in the program. It checks a Boolean expression. A correct program must ensure that the value of this Boolean expression is true. If this value is false, if the program is in an incorrect state, the system will give a warning or exit. Generally, assertion is used to ensure the most basic and critical correctness of the program. The assertion check is usually enabled during development and testing. To improve performance, the assertion check is usually disabled after the software is released.
7. String S = new string ("XYZ"); several string objects are created.
A: Two. One character object and one character object reference the object.
8. How much is math. Round (11.5? Math. Round (-11.5) and so on
A: math. round (11.5) = 12; math. round (-11.5) =-11; the round method returns a long integer closest to the parameter. After the parameter is added to 1/2, the floor is obtained.
9. Short S1 = 1; S1 = S1 + 1; what is the error? Short S1 = 1; S1 + = 1; what is the error?
Answer: Short S1 = 1; S1 = S1 + 1; (S1 + 1 is an int type, which requires forced conversion) Short S1 = 1; S1 + = 1; (can be compiled correctly)
10. Does Java have a goto?
A: Reserved Words in Java are not currently used in Java.
11. Does the array have the length () method? Does string have the length () method?
A: The array does not have the length () method. It has the Length attribute. The string has the length () method.
12. Differences between overload and override. Can the overloaded method change the type of the returned value?
A: overriding and overloading are different manifestations of Java polymorphism. Overriding is a manifestation of the polymorphism between the parent class and the Child class, and overloading is a manifestation of the polymorphism in a class. If a subclass defines a method with the same name and parameter as its parent class, we say this method is overwritten ). When a subclass object uses this method, the definition in the subclass is called. For it, the definition in the parent class is "blocked. If multiple methods with the same name are defined in a class, they may have different numbers of parameters or different parameter types, it is called overloading ). The overloaded method can change the type of the returned value.
13. The elements in the set cannot be repeated. How can we identify whether the elements are repeated or not? Is = or equals () used ()? What are their differences?
A: The elements in the set cannot be repeated. Use the iterator () method to identify whether the elements are repeated or not. Equals () is used to determine whether two sets are equal
The equals () and = Methods Determine whether the reference value points to the same object equals () is overwritten in the class, so that when the content and type of the two separated objects match, the true value is returned.
14. Give me the most common runtime exception
A: Common runtime exceptions include the following arithmeticexception, arraystoreexception, exceptions, exceptions, cannotredoexception, cannotundoexception, classcastexception, cmcmexception, exceptions, domexception, emptystackexception, cause, expires, imagingopexception, failed, missingresourceexception, failed, failed, nullpointerexception, profiledataexception, providerexception, rasterformatexception, securityexception, systemexception, undeclaredthrowableexception, unmodifiablesetexception, unsupportedoperationexception
15. What are the differences between error and exception?
A: Error indicates that the restoration is not an impossible but difficult case. For example, memory overflow. It is impossible to expect the program to handle such a situation
Exception indicates a design or implementation problem. That is to say, it indicates that if the program runs normally, it will never happen.
16. Does list, set, and map inherit from the collection interface?
A: List, set Yes, map is not
17. What are the differences between abstract class and interface?
A: The class that declares the existence of a method without implementing it is called abstract class. It is used to create a class that reflects some basic behaviors and declare a method for this class, however, this class cannot be implemented in this class. You cannot create an abstract instance. However, you can create a variable whose type is an abstract class and point it to an instance of a specific subclass. Abstract constructors or abstract static methods are not allowed. The subclasses of abstract classes provide implementation for all abstract methods in their parent classes. Otherwise, they are also abstract classes. Instead, implement this method in the subclass. Other classes that know their behavior can implement these methods in the class.
An interface is a variant of an abstract class. All methods in the interface are abstract. Multi-inheritance can be achieved by implementing such an interface. All methods in the interface are abstract, and none of them have a program body. The interface can only define static final member variables. The implementation of an interface is similar to that of a subclass, except that the implementation class cannot inherit behaviors from the interface definition. When a class implements a special interface, it defines (to be given by the program body) all the methods of this interface. Then, it can call the interface method on any object that implements the interface class. Because there is an abstract class, it allows the interface name as the type of the referenced variable. Normally, dynamic Association editing will take effect. The reference can be converted to the interface type or from the interface type. The instanceof operator can be used to determine whether the class of an object implements the interface.
18. can abstract methods be both static, native, and synchronized?
A: neither of them can be used.
19. Can an interface inherit an interface? Can an abstract class implement the (implements) interface? Whether the abstract class can inherit the concrete class)
A: The interface can inherit the interface. Abstract classes can be implemented (implements) interfaces. Whether abstract classes can inherit object classes, but the premise is that object classes must have clear constructors.
20. Can constructor be overwritten?
A: constructor cannot be inherited, so overriding cannot be overwritten, but overloading can be overloaded.
21. Can I inherit the string class?
A: The string class is a final class, so it cannot be inherited.
22. If there is a return statement in try {}, will the code in finally {} following this try be executed? When will it be executed? Before or after return
A: Yes. It will be executed before return.
23. Use the most efficient method to calculate the number equal to 2x8
Answer: 2 <3
24. The two objects have the same value (X. Equals (y) = true), but different hash codes are available.
A: No. The same hash code exists.
25. when an object is passed as a parameter to a method, this method can change the property of the object and return the changed result. In this case, whether it is a value transfer or a reference Transfer
A: value transfer. Java programming language only supports value passing parameters. When an object instance is passed as a parameter to a method, the parameter value is a reference to the object. The object content can be changed in the called method, but the object reference will never change.
26. Can swtich be applied to byte, long, or string?
A: expr1 is an integer expression in witch (expr1. Therefore, the parameters passed to the switch and case statements should be int, short, Char, or byte. Long and string cannot work on swtich.
27. Differences between arraylist and vector, and between hashmap and hashtable
A: arraylist and vector are mainly used in two aspects.
1. Synchronization: the vector is thread-safe, that is, synchronous, while the arraylist is not secure or synchronous
2. Data growth: When we need to increase, the vector grows to the original training by default, while the arraylist is half of the original growth.
Hashmap and hashtable are mainly used in three aspects.
I. Historical Reasons: hashtable is based on the obsolete dictionary class, And hashmap is an implementation of the map interface introduced by Java 1.2.
2. Synchronization: hashtable is thread-safe, that is, synchronous, while hashmap is not secure or synchronous.
3. Value: Only hashmap allows you to use a null value as the key or value of a table entry.
28. Can a Chinese character be stored in a char variable? Why?
A: It can be defined as a Chinese character. Because Java uses unicode encoding and a char occupies 16 bytes, it is okay to put a Chinese character.
29. What is GC? Why GC?
A: GC is the meaning of garbage collection (gabage collection). Memory Processing is a vulnerable issue for programmers, if you forget or make a wrong memory recycle, the program or system may be unstable or even crashed. The GC function provided by Java can automatically monitor whether the object exceeded the scope to automatically recycle the memory, the Java language does not provide a display method for releasing allocated memory.
30. Is float F = 3.4 correct?
A: incorrect. The precision is not accurate. Forced type conversion should be used, as shown below: Float F = (float) 3.4
31. describes the collection framework in Java (including how to write your own data structure )?
A: The collection framework is as follows:
│ Invalid parameter list
│ ├ Arraylist
│ Vector
│ Elastic Stack
Sorted set
├ Hashtable
├ Hashmap
└ Weakhashmap
Collection is the most basic collection interface. A collection represents a group of objects, that is, elements of the collection)
Map provides key-to-value ing
32. abstract classes and interfaces?
A: abstract classes and interfaces are used for abstraction, but abstract classes (in Java) can have their own partial implementations, while interfaces are completely an identifier (with multiple inheritance features at the same time ).
Java class implementation of the ordinal method is to implement the java. Io. serializable Interface
Comparable and comparator interfaces must be implemented in the Collection framework.
33. Differences between string and stringbuffer.
A: The length of string is unchangeable, and the length of stringbuffer is variable. If you often operate on the content in the string, especially when the content is to be modified, use stringbuffer. If the string is needed at last, use the tostring () method of stringbuffer.
34. Differences between final, finally and finalize
A: Final? Modifier (keyword) If a class is declared as final, it means that it cannot generate a new subclass and cannot be inherited as a parent class. Therefore, a class cannot be declared both abstract and final. Declare variables or methods as final to ensure that they are not changed during use. Variables declared as final must be declared with an initial value, which can only be read and cannot be modified in future references. Methods declared as final can only be used and cannot be reloaded.
Finally? Finally blocks are provided for troubleshooting. If an exception is thrown, the matched catch clause is executed, and the control enters the Finally block (if any)
Finalize? Method Name. Java technology allows you to use the finalize () method to clear objects from the memory before the Garbage Collector clears them. This method is called by the garbage collector when it determines that this object is not referenced. It is defined in the object class, so all classes inherit it. Subclass overwrites the finalize () method to sort system resources or perform other cleanup tasks. The finalize () method is called before the Garbage Collector deletes an object.
35. What are the features of object orientation?
A: There are four main aspects:
1. Abstraction:
Abstraction is to ignore those aspects irrelevant to the current target in a topic, so that you can pay more attention to the aspects related to the current target. Abstraction is not intended to understand all the problems, but to select a part of the problem. Abstract: Process abstraction and data abstraction.
2. Inheritance:
Inheritance is a hierarchical model that connects classes and allows reuse of encouraging classes. It provides a way to clearly express commonalities. A new class of an object can be derived from an existing class. This process is called class inheritance. The new class inherits the features of the original class. The new class is called the derived class (subclass) of the original class, and the original class is called the base class (parent class) of the new class ). A derived class can inherit methods and instance variables from its base class, and the class can modify or add new methods to make it more suitable for special needs.
3. encapsulation:
Encapsulation is to enclose the process and data. Data access can only be performed through the defined interface. Object-oriented computing begins with the basic concept that the real world can be depicted as a series of completely autonomous and encapsulated objects that access other objects through a protected interface.
4. Polymorphism:
Polymorphism allows different types of objects to respond to the same message. Polymorphism includes parameterized polymorphism and inclusion polymorphism. The polymorphism language has the advantages of flexibility, abstraction, behavior sharing, and code sharing, which effectively solves the same name problem of application functions.
36. Is string the most basic data type?
A: The basic data types include byte, Int, Char, long, float, double, Boolean, and short.
Java. Lang. string class is of the final type. Therefore, it cannot be inherited or modified. To improve efficiency and save space, we should use the stringbuffer class
37. What is the difference between int and integer?
A: Java provides two different types: The reference type and the original type (or the built-in type ). Int Is the original data type of Java, and integer is the encapsulation class provided by Java for int. Java provides encapsulation classes for each original type.
Original encapsulation class, booleanboolean, charcharacter, bytebyte, shortshort, intinteger, Longlong, floatfloat, doubledouble
The behavior of the reference type and the original type is completely different, and they have different semantics. The reference type and the original type have different features and usage, they include: size and speed problems, which type of data structure is stored, the default value specified when the reference type and original type are used as instance data of a class. The default value of the instance variables referenced by the object is null, and the default value of the original type instance variables is related to their types.
38. What are the similarities and differences between runtime exceptions and general exceptions?
A: An exception indicates an abnormal state that may occur during the running of the program. An exception indicates an exception that may occur during common operations on the virtual machine. It is a common running error. The Java compiler requires that methods must declare and throw possible non-runtime exceptions, but do not require that they throw uncaptured runtime exceptions.
39. Specify the storage performance and features of arraylist, vector, and sorted list.
A: Both arraylist and vector use arrays to store data. The number of elements in this array is greater than that in actual storage for adding and inserting elements. Both Allow Indexing elements by serial number directly, however, inserting elements involves memory operations such as array element movement, so index data is fast and data insertion is slow. Because vector uses the Synchronized Method (thread-safe), its performance is generally inferior to that of arraylist, the sorted list uses a two-way linked list for storage. Data indexed by serial number needs to be traversed in the forward or backward direction. However, when inserting data, you only need to record the items before and after this item, so the insertion speed is fast.
40. Differences between hashmap and hashtable
A: hashmap is a lightweight Implementation of hashtable (non-thread-safe implementation). They have completed the map interface. The main difference is that hashmap allows null key values ), because of non-thread security, the efficiency may be higher than that of hashtable.
Hashmap allows null as the key or value of an entry, whereas hashtable does not.
Hashmap removes the contains method of hashtable and changes it to containsvalue and containskey. The contains method is easy to misunderstand.
Hashtable inherits from the dictionary class, while hashmap is an implementation of the map interface introduced by java1.2.
The biggest difference is that the hashtable method is synchronize, but hashmap is not. When multiple threads access hashtable, they do not need to implement synchronization for their own methods, hashmap must provide external synchronization for it.
The hash/rehash algorithms used by hashtable and hashmap are roughly the same, so there is no big difference in performance.
41. What is the difference between heap and stack?
A: A stack is a linear set. The operations for adding and deleting elements should be completed in the same segment. The stack is processed as follows. Heap is an element of stack.
42. Similarities and Differences between Java interfaces and C ++ virtual classes
A: Because Java does not support multi-inheritance, it is possible that a class or object must use methods or attributes in several classes or objects respectively. The existing single Inheritance Mechanism cannot meet the requirements. Compared with inheritance, interfaces are more flexible because they do not have any implementation code. After a class implements an interface, this class implements all the methods and attributes in the interface, and the attributes in the interface are under the default state are public static, 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 the Java Semantic Rules, the Java Virtual Machine will indicate an error as an exception. There are two types of violation of Semantic Rules. One is the built-in semantic check of the Java class library. For example, if the array subscript is out of the range, indexoutofboundsexception is triggered. When a null object is accessed, nullpointerexception is thrown. Another scenario is that Java allows programmers to extend this semantic check. programmers can create their own exceptions and choose when to use the throw keyword to cause exceptions. All exceptions are subclasses of Java. Lang. thowable.
43. Advantages and principles of garbage collection. Two recovery mechanisms are considered.
A: A notable feature of Java is the introduction of the garbage collection mechanism, which helps C ++ programmers solve the most troublesome memory management problems, it makes memory management unnecessary for Java programmers when writing programs. Because of the garbage collection mechanism, objects in Java do not have the "Scope" concept, and only objects can be referenced with "Scope ". Garbage collection can effectively prevent memory leakage and effectively use available memory. The garbage collector is usually used as a separate low-level thread to clear and recycle objects that have been killed in the memory heap or are not used for a long time, programmers cannot call the Garbage Collector to recycle an object or all objects in real time. The collection mechanism involves generational replication, garbage collection, marking, and incremental garbage collection.
44. What are the collection classes you know? What are the main methods?
A: The most common collection classes are list and map. The specific implementation of list includes arraylist and vector, which are variable-size lists and are suitable for building, storing, and operating the list of elements of any type of object. List is applicable to accessing elements by Numerical index.
Map provides a more general method for storing elements. The Map Collection class is used to store element pairs (called "keys" and "values"). Each key maps to a value.
45. How does JVM load class files?
A: In JVM, class loading is implemented by classloader and its subclass. Java classloader is an important Java runtime system component. It is responsible for finding and loading classes of class files at runtime.
46. What are the methods for sorting? List
A: The sorting methods include insert sorting (direct insertion sorting and Hill sorting), exchange sorting (Bubble sorting and quick sorting), and select sorting (Direct selection of sorting and heap sorting ), merge Sorting and distribute sorting (Box sorting and base sorting)
Pseudo code for fast sorting.
// Use the quick sorting method to sort a [0: n-1]
Select an element from a [0: n-1] As m I d l e, which is the fulcrum
Divide the remaining elements into two left and r I g h t, so that the elements in L E F T are less than or equal to the fulcrum, and the elements in right are greater than or equal to the Fulcrum.
Recursively sort left by using the quick sorting method
Recursively sort right using the quick sorting method
The result is l e f t + m I d l e + r I g h t.
47. How to handle exceptions in Java? What are the meanings of keywords: throws, throw, try, catch, and finally? Can I throw an exception in the try block?
A: Java uses object-oriented methods to handle exceptions, classify various exceptions, and provide good interfaces. In Java, each exception is an object, which is an instance of the throwable class or other subclass. When a method encounters an exception, an exception object is thrown. The object contains the exception information. The method that calls this object can capture the exception and handle it. Java exception handling is implemented through five keywords: Try, catch, throw, throws, and finally. Generally, try is used to execute a program. If an exception occurs, the system throws an exception. In this case, you can catch it by its type, or finally (finally) is handled by the default processor.
Use try to specify a program to prevent all "exceptions. The catch clause should be followed by the try program to specify the type of the "exception" you want to capture.
Throw statements are used to explicitly throw an "exception ".
Throws is used to indicate various "exceptions" that a member function may throw ".
Finally ensures that a piece of code is executed no matter what "exception" occurs.
You can write a try statement outside a member function call, and write another try statement inside the member function to protect other code. Every time a try statement is encountered, the framework of "exception" is placed on the stack until all try statements are completed. If the try statement at the next level does not process an "exception", the stack will be opened until a try statement that handles this "exception" is encountered.
48. Can a ". Java" source file contain multiple classes (not internal classes )? What are the restrictions?
A: Yes. Only one class name must be the same as the file name.
49. How many types of streams are there in Java? JDK provides some abstract classes for each type of stream for inheritance. which classes are they?
A: byte streams and byte streams. Byte streams are inherited from inputstream outputstream, and bytes streams are inherited from inputstreamreader outputstreamwriter. There are many other streams in the Java. Io package, mainly to improve performance and ease of use.
50. Is there any memory leakage in Java? Please briefly describe it.
A: Yes. Memory leakage may occur when self-implementing the heap data structure. For more information, see objective Java.
51. What is the mechanism for implementing polymorphism in Java?
A: overriding and overloading are different manifestations of Java polymorphism. Overriding is a manifestation of the polymorphism between the parent class and the Child class, and overloading is a manifestation of the polymorphism in a class.
52. What is the basic principle of the garbage collector? Can the Garbage Collector recycle memory immediately? Is there any way to actively notify the virtual machine to perform garbage collection?
A: For GC, when a programmer creates an object, GC starts to monitor the address, size, and usage of the object. Generally, GC records and manages all objects in heap by Directed Graphs. This method is used to determine which objects are "reachable" and which objects are "inaccessible ". When GC determines that some objects are "inaccessible", GC has the responsibility to recycle the memory space. Yes. Programmers can manually execute system. GC () to notify the GC to run, but the Java language specification does not guarantee that GC will be executed.
53. What are the differences between static variables and instance variables?
A: static I = 10; // constant class A; A. I = 10; // variable
54. What is Java serialization and how to implement Java serialization?
A: serialization is a mechanism used to process object streams. The so-called object stream is to stream the object content. You can perform read and write operations on Streaming objects, or transfer streaming objects between networks. Serialization aims to solve the problems caused by read/write operations on Object streams.
Serialization implementation: implement the serializable interface for the class to be serialized. There is no implementation method for this interface. implements serializable is only to mark that the object can be serialized, then, an output stream (such as fileoutputstream) is used to construct an objectoutputstream (Object stream) object. Then, the writeobject (Object OBJ) of the objectoutputstream object is used) method, you can write the object whose parameter is OBJ (that is, save its status). To restore the object, use the input stream.
55. Can I call non-static methods from inside a static method?
A: No. If it contains the method () of the object, object initialization cannot be ensured.
56. When writing the clone () method, there is usually a line of code. What is it?
A: clone has a default action. Super. Clone () is responsible for generating the correct size of space and copying data by bit.
57. In Java, how does one jump out of the current multi-nested loop?
A: use the break; Return method.
58. What are the features of the interfaces list, map, and set when accessing elements?
A: The list holds elements in a specific order. duplicate elements are allowed. Set cannot have repeated elements and can be sorted internally. Map stores the key-value, which can be multiple values.
59. You can name five common classes, packages, and interfaces.
A: common classes: bufferedreader bufferedwriter filereader filewirter string integer
Common packages: Java. Lang java. AWT java. Io java. util java. SQL
Common interfaces: Remote list map document nodelist
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: 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.