Java basics-interview question 1

Source: Internet
Author: User

1. What are classes and objects?
A: objects are entities in the real world. Objects correspond to entities one by one. That is to say, every entity in the real world is an object. It is a specific concept.
A class is a set of entities with certain common features. It is an abstract concept. In programming languages, a class is an abstract data type, it is an abstraction of all entities with the same features.
2. attributes and methods?
A: different objects have the same features and may be abstracted into certain classes. These features can be basically divided into two categories: one is to describe the static state of objects, that is, the attributes of objects, in program design, it can be called a variable. The other is to describe the object action, that is, the object method. In program design, we call it a function. Attributes and methods are the two basic elements of an object and the core of our subsequent programming work.
3. What is encapsulation?
A: As long as there are enough methods, there is no need to directly operate on Object Attributes. You only need to call these methods to implement the task to be completed. This phenomenon is called encapsulation, it encapsulates object attributes in an object through operations on its attributes, and all the operations on objects and external entities are implemented through its own methods, effectively hides object attributes inside the object.
4. What are precautions for writing java files?
A: Write a Java file in Notepad. You must enclose the file name and extension in double quotation marks when saving the file. Otherwise, the file is saved as a text file by default. If the Java file name to be saved is program1.java, when saving, you must enter "program1.java" in the file name text box ".
5. How to compile a Java program? How to execute Java programs?
A: Click Start | run the command, Enter cmd on the command line, and press enter (Enter command in window98 and press Enter) to open a command window, convert the directory to the directory where the Java source program is written, and enter javac filename. java
Enter Java filename in the Command window,
6. What is the basic data type?
A: The data types of Java can be divided into four categories: integer, floating point, random, and Boolean. Integers can be divided into byte, short, Int, and long. floating point numbers can be divided into float and double.

7. What is oop? What is a class? Compare the relationships between classes and object instances.
A: Oop is short for object_oriented programming. This is mainly to distinguish it from the previous process-oriented programming! It refers to the organization and construction of a system from the perspective of objects. It integrates functional abstraction and data abstraction, which can reduce the coupling between data and the chance of code errors.
The use of object-oriented programming technology allows software developers to write code in a way that people think about problems in the real world, so that software developers can better use code to directly express existing objects in reality, map the problem space directly to the solution space!

Class: In the object-oriented programming, class specifically uses "class" to represent the User-Defined abstract data type (user_defined abstract type ). It abstracts multiple objects with the same status, operation, and access mechanism. Class has three main features: inheritance, data hiding, and polymorphism. These three features of the class can better represent things in the real world. A class is a common abstraction of the same class object instance, and an object is a class instantiation. An object is usually used as a computer simulated mind to represent the abstraction of the real world. An object is like a software module and can be used by users.
Provides a series of services, such as changing the object status, testing, and passing messages. Class defines the implementation details or data structure of objects. The class is static, the object is dynamic, and the object can be seen as a running class. Class is responsible for generating objects. class can be treated as the factory of the production object ).
8. What are common data structures? Please enumerate some. (No less than 5)
A: linked list, stack, binary tree, queue, graph, heap, and set.
1. What are the features of object orientation?
A: abstraction, inheritance, encapsulation, and polymorphism...
<1. Abstraction: Abstraction ignores the 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 clear way to 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 of the original class (subclass), and the original class is called the new class
Base Class (parent 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: encapsulate processes (methods) and data. Access to data 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.
2. 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.

(Overriding ). When a subclass object uses this method, it calls the definition in the subclass. 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.
3. What is the difference between abstract class and interface?

Answer: (1) the interface can be implements multiple times. The abstract class can only be extends (inherited ).
(2) Only interfaces are defined. abstract classes can be defined and implemented.
(3) The default field definition of the interface is public static final. The default field of the abstract class is "friendly" (this package is visible)
Abstract classes and interfaces are used for abstraction, but abstract classes (in Java) can be partially implemented.
The interface is completely an identifier (with multiple inheritance features at the same time ).

The class that declares a method rather than 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 conversion, instanceof
The operator can be used to determine whether an object's class implements an interface.
4. after an object is passed as a parameter to a method, this method can change the properties of this object and return the changed result. Is it a value transfer or a reference transfer?

A: value transfer. The Java programming language only transmits parameters by values. 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.

5. What are the 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.

6. 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.
7. Advantages and principles of garbage collection. There are two recovery mechanisms to be considered. How can I optimize the program? Can the Garbage Collector recycle memory immediately? Is there any way to proactively notify virtual machines to recycle garbage?

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.
The basic principle of the garbage collector is: For GC, when a programmer creates an object, GC starts to monitor the address, size, and usage of the object. Generally, GC records all objects in the 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.
Memory can be recycled immediately. 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.
8. What is GC? Why does GC exist?
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.

To request garbage collection, you can call one of the following methods:
System. GC ();
Runtime. getruntime (). GC ();
9. Simple Principle and Application of the 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.
10. 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.
11. What is the difference 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. error is a subclass of throwable, indicating that the application does not need to capture serious errors. Once this happens, the program is immediately terminated.
Exception indicates a design or implementation problem. That is to say, it indicates that if the program runs normally, it will never happen.
12. 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.
13. Introduction to the Collection framework in Java (including how to write your own data structure )?

A: The collection framework is as follows:

Collection
Shortlist
│ Invalid parameter list
│ ├ Arraylist
│ Vector
│ Elastic Stack
Sorted set
Map
├ 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.
14. Differences between collection and collections.
A: collection is an interface under java. util. It is the parent interface of various collection structures.
Collection is the upper-level interface of the Collection class. Its inherited interfaces include set and list.
Collections is a Java. util class that contains various static methods related to set operations.
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.

15. 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.

16. hashtable principle, and the difference between hashmap and hashtable
A: hashtable principle: the storage location of a node is determined by the key code of the node, that is, the key code K of a given node, through a certain function relationship H (hash function ), obtain the function value H (k), which is interpreted as the storage address of the node.
Hashmap is similar to hashtable, but hashmap is non-synchronous (unsynchronizded) and can take null as the key code.
The difference between hashmap and hashtable.
Hashmap is a lightweight Implementation of hashtable (non-thread-safe implementation). It completes the map interface and maps unique keys to specific values. The main difference is that hashmap allows null key values. Because of non-thread security, the efficiency may be higher than 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.
17. 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;
Vector uses the Synchronized Method (thread-safe), which generally has poor performance compared to arraylist. The sorted list uses a two-way linked list for storage. Data indexed by serial numbers needs to be traversed in the forward or backward directions, however, when inserting data, you only need to record the items before and after this item, so the insertion speed is relatively high.
18. What is the difference between arraylist and vector? What is the difference 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.

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.