Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common basic knowledge questions of Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you what are the relevant knowledge points of the common basic knowledge questions of Java, the content is detailed, and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

1. The size of the eight basic data types and their wrapper classes

Data type encapsulates class size byteByte1 byte shortShort2 byte intInteger4 byte longLong8 byte floatFloat4 byte doubleDouble8 byte booleanBoolean/charCharacter2 byte

2. Can switch use string as a parameter?

The variable type in the switch statement can make byte,short,int,char. After jdk1.7, you can use the String type, which is judged by converting String to int through the String.hashcode in switch.

Third, the difference between equals and =

The = = operator is used to compare whether the values of two variables are equal, that is, to compare whether the storage address of the variable in memory is the same. The String class inherits from the Object class when the equals () method is used to detect whether the contents of the two objects are the same.

4. String s = new String ('abc'); how many object objects have been created?

A variable s of type String is created. If the literal "abc" does not appear before the class is loaded here, loading here creates a String constant object corresponding to "abc". On a JVM that conforms to the specification, the new keyword here creates a String object.

5. What are the common methods of Object?

Clone () creates a bin to return a copy of this object

Equals () judgment

Getclass () returns the running class of object

Hashcode () returns the hash code value of the object

Notify () wakes up a single process waiting for object listeners

NotifyAll () wakes up all processes waiting for object listeners

Wait () causes the current thread to wait until another thread calls the object's notify () method or notifyAll () method

ToString () returns a string representation of this object

Finalize () when the garbage collection determines that the object is not needed, the garbage collector calls this method

6. Four citations of Java, scenarios used

Strong reference: the garbage collector will not recycle

Soft reference: if there is enough memory space, the garbage collector will not collect it. If there is not enough memory space, the garbage collector will collect it.

Weak references: once an object with only weak references is found, the garbage collector collects it.

Virtual reference: if it is found that the object also has a virtual reference, the virtual reference will be added to the reference queue associated with it before the object is recycled.

VII. The difference between static variables and instance variables

Static variables are preceded by the keyword static, while instance variables are not.

An instance variable is a property that belongs to an object, and an instance object must be created before the instance variable allocates space before it can be used. Static variables do not belong to any instance objects, but belong to classes, also known as class variables. As long as the program loads the bytecode of the class and does not have to create any instance objects, space will be allocated. In short, static variables can be used directly without creating any objects, while instance variables need to create instance objects before they can be used.

VIII. The difference between Overload and Override

Overloaded Overload means that there can be multiple methods with the same name in the same class, but these methods have different parameter lists, that is, different parameter parameters or parameter types. Of course, the return values can be different when overloaded, but if the parameter list is exactly the same, you cannot overload through inconsistent return types, which is not allowed.

Overriding Override means that the method in the subclass can have exactly the same name and parameters as the method in the parent class. When this method is called through an object created by the subclass, the method defined in the subclass is called, that is, the method in the subclass overrides the method of the parent class. When a subclass overrides a parent method, it can only throw fewer or smaller exceptions than the parent class. The return of the overridden method must be consistent with that of the overridden method.

IX. The difference between abstract classes and interfaces

Abstract class can have default method to implement, can have constructor, can have main method to run, can directly add the implementation method interface to this class without default method to implement, no constructor, can not use main method to run, add method in the interface to add method in the concrete implementation class.

The object-oriented features and meanings of Java

Encapsulation: the purpose of encapsulation is to achieve "high cohesion, low coupling" of the program, and to prevent the change caused by the interdependence of the program. Encapsulation is to ensure that the methods that operate on the same thing and the related methods are put in the same class, and the methods and the data operated by others are put in the same class.

Abstraction: abstraction is to find out the similarities and commonalities of things, and then put them into the same category. This class only considers the similarities and commonalities of these things, ignoring factors that are not related to the current topic.

Inheritance: subclasses inherit the contents of the parent class as their own, and can add new content or modify the contents of the parent class to better meet special needs. The reusability and expansibility of the program are improved.

Polymorphism: polymorphism means that the specific type pointed to by the reference variable defined in the program and the method calls made through the reference variable are not determined during programming, but are determined during the run of the program, that is, a reference variable will point to the instance object of which class, and the method call issued by the reference variable must be determined during the run of the program.

11. Realization of java Polymorphism

Interface implementation, inheriting the parent class for method rewriting

Method overloading occurs in the same class.

12. The difference between run-time exceptions and general exceptions

An exception indicates an abnormal state that may occur while the program is running. Run-time exceptions represent exceptions that may be encountered in the usual operation of a virtual machine and are a common running error. The java compiler requires methods to declare that non-runtime exceptions may be thrown, but not to declare that uncaught exceptions must be thrown.

13. How does the Java language handle exceptions? what does throws,throw,try catch finally stand for? can exceptions be thrown in try blocks?

Java handles exceptions through object-oriented methods, classifies different exceptions, and provides a good interface. In Java, each exception is an object, which is an instance of the Throwable class or other subclasses. When a

After an exception occurs in the method, an exception object is thrown, which contains exception information, and the method that calls this object can catch the exception and handle it. The exception handling of Java is implemented through five keywords: try, catch, throw, throws and finally. Normally, try is used to execute a program. If an exception occurs, the system will throws an exception. You can catch it by its type, or finally (finally) will be handled by the default processor.

Use try to specify a program to prevent all "exceptions". Immediately after the try program, a catch clause should be included to specify the type of "exception" you want to catch.

The throw statement is used to explicitly throw an "exception"

Throws is used to mark various "exceptions" that may be thrown by a member function.

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 another try statement inside that member function to protect other code. Whenever a try statement is encountered, the "exception" framework is placed on the stack until all the try statements are completed

If the next-level try statement does not handle some "exception", the stack expands until a try statement that handles such an "exception" is encountered.

Will return,finally still be implemented in try catch finally,try?

Finally statements are always executed

If there are return statements in try and catch and no return in finally, then modifying data except wrapper type and static variable and global variable in finally will not have any effect on the variables returned in try and catch (wrapper type, static variable will change, global variable)

Try not to use return statements in finally. If you do, the return statements in try and catch will be ignored, and the exceptions in try and catch will also be ignored, thus blocking the occurrence of errors.

Avoid throwing exceptions again in finally. Once an exception occurs in finally, code execution will throw exception information in finally, and exceptions in try and catch will be ignored.

15. The difference among final, finally and finalize in Java

Final is used to declare properties, methods, and classes, respectively, indicating that properties are immutable, methods are not overridden, and classes are not inheritable; for internal classes to access local variables, local variables must be defined as final types, for example, a piece of code.

Finally is part of the structure of the exception handling statement, which means that it is always executed

Finalize is a method of the Object class, which is called when the garbage collector executes, and can override other resource collection when this method provides garbage collection, such as closing files, and so on. JVM does not guarantee that this method will always be called.

The difference between String, StringBuffer and StringBuilder

String represents a string whose content cannot be modified, and StringBuffer represents a string whose content can be modified.

String overrides the equals () method and the hashcode () method, while StringBuffer does not overwrite both methods, so there is a problem when the StringBuffer object is stored in the java collection class

StringBulider also represents a string whose content can be modified, but its thread is unsafe and efficient.

17. The difference between error and exception

Error says it is possible to recover but a serious problem that cannot be dealt with by the program.

Exception represents a design or implementation problem.

XVIII. Exception handling mechanism and simple principles and applications in Java

When the JAVA program violates the semantic rules of JAVA, the JAVA virtual machine represents the error as an exception. Violations of semantic rules include two situations:

One is the semantic checking built into the JAVA class library. For example, if the array subscript is out of bounds, it will cause IndexOutOfBoundsException; to access the object of null and raise NullPointerException.

Another scenario is that JAVA allows programmers to extend this semantic checking, allowing programmers to create their own exceptions and freely choose when to throw exceptions with the throw keyword. All exceptions are subclasses of java.lang.Thowable.

XIX. Common runtime exceptions

System exceptions are a subclass of RuntimeException. Common system exceptions are:

ArrayIndexOutOfBoundsException-Array out of bounds access

ClassCastException-Type conversion exception

NullPointerException-elements that attempt to access a variable, method, or empty array of an empty object

IllegalArgumentException-invalid parameters for the method

The NoClassDefFoundException-JAVA runtime system cannot find the referenced class

The elements in Set cannot be repeated. What method can be used to distinguish repetition from non-repetition?

The element in Set is the only one that cannot be repeated, and whether the element is repeated using the equals () method is determined.

The equals () method and the = = method determine whether the reference value points to the same object equals () is overridden in the class in order to return a true value if the contents and types of the two separate objects match.

21, the difference between HashMap and Hashtable

Hashtable is based on the Dictionary class, and HashMap is an implementation class of the Map interface

Hashtable is thread-safe, that is, synchronous; HashMap threads are not safe, not synchronous

HashMap can use null values as key or value.

Differences between 22, HashMap, LinkedHashMap and TreeMap

HashMap stores data according to the hashcode value of the key, and its value can be obtained directly according to the key. It has a fast access speed, and the data obtained is completely random.

LinkedHashMap saves the insertion order of records. When traversing with Iterator, the first thing you get must be the data that is inserted first. You can sort the data with parameters during construction and sort them according to the number of applications.

TreeMap implements the SortMap interface, which can sort the records it saves by key. The default is ascending sort, or you can specify the sort comparator, and when you traverse, you get the sorted records.

23, the underlying implementation of HashMap, LinkedHashMap, ConcurrentHashMap, ArrayList, LinkedList.

HashMap is the combination of two structural arrays and linked lists in java data structures. HashMap underlying array, each item in the array is another linked list. The program will first determine the storage location of the Entry in the array according to the return value of the hashcode () method of key. If there is no element in this location, the element will be placed in this position. If the key of the two Entry is the same, equals will be called. If the return value is true, the original value will be overwritten, and the return false will form an Entry chain, located in the header.

The underlying implementation of ArrrayList is an array. When performing the add operation, it will first check whether the size of the array can accommodate the new elements, and expand if it is not enough. The original data is then copied to the new array.

The bottom layer of LinkedList is a linked list, which implements the operation of adding, deleting, changing and querying exactly the same as in the data structure, and the insertion is orderly.

The underlying structure of LinkedHashMap is a double-linked list, other logic processing is the same as HashMap, there is no lock protection, there is a risk when using multithreading.

ConcurrentHashMap is composed of segment array structure and HashEntry array structure. Segment acts as a lock in ConcurrentHashMap, and HashEntry is used to store key-value pair data. The structure of segment is array and linked list, there is a HashEntry in a segment, and each HashEntry is a linked list structure element. When you modify the data in HashEntry, you need to obtain its corresponding segment lock first. There are 16 segment by default for each ConcurrentHashMap.

24, iterator Iterator

Iterator provides a unified interface for traversing the set elements of operations, and the Collection interface implements the Iterator interface. Each collection returns an instance by implementing the iterator () method in the Iterator interface, and then iterates on the element, but you cannot use the collection method to delete the element when iterating the element, otherwise an exception will be thrown, which can be deleted using the remove () method in the Iterator interface.

25, the characteristics and usage of Map, Set, List, Queue and Stack.

1. Map is stored in the form of key-value pairs, in which key is the only non-repeatable, and value can be repeated. When the inserted value is the same as key, the existing ones will be overwritten. He has several specific implementation classes, including Treemap and HashMap,TreeMap are ordered and HashMap is unordered.

2. List is orderly and repeatable

| |-ArrayList |

The underlying data structure is an array, with fast query, slow addition and deletion, unsafe thread and high efficiency.

| |-Vector |

The underlying data structure is an array, with fast query, slow addition and deletion, unsafe thread and high efficiency.

| |-LinkedList |

The underlying data structure is linked list, slow query, add and delete blocks, thread safety and low efficiency.

3. Set is unordered and unique.

| |-HashSet |

The underlying data structure is a hash table.

How to ensure the uniqueness of elements:

Depends on two methods, hashCode () and equals ()

| |-LinkedHashSet |

The underlying data structure is a linked list and a hash table. The elements are ordered by the linked list and unique by the hash table.

| |-TreeSet underlying data structure is a red-black tree |

How to ensure the sorting of elements:

Natural sorting: let the class to which the element belongs implement the Comparable interface

Comparator sort: let the collection receive an Comparator implementation class object

How to ensure the uniqueness of elements:

It is determined according to whether the return value of the comparison is 0.

4. The Query queue follows the first-in-first-out principle and does not allow the insertion of null values, in which the corresponding methods for entering and leaving the queue are provided. It is recommended to use the offer () method to add elements and use the poll () method to delete elements.

5. Stack follows the last-in-first-out principle and inherits from Vector. He extends the Vector class through five operations, which provides push and pop operations, as well as the peek () method to de-stack vertices, and the empty method to test whether the stack is empty.

6. Usage:

If stack, queue and other operations are involved, it is recommended to use List

LinkedList is recommended for quick insertion and deletion of elements

ArrayList is recommended for fast random access to elements

26, Collection packet structure

Collection is the parent interface of the collection class and is a single-column collection. The main interfaces that inherit him are Set and List.

The subinterfaces of the Set interface are: HashSet,TreeSet

The subinterfaces of the List interface are: Arraylist,LinkedList,Vector

27, the difference between Collection and Collections.

Collection is the parent interface of the collection class. The interfaces that inherit it are Set and List.

Collections is a helper class for collection classes, it provides a series of static methods to achieve collection search, sorting, thread safety and other operations.

28. What interfaces should be implemented in the Colection framework?

Comparable: contains only the compareTo () method

Comparator:compare () and equals ()

29. The structure of the Collection framework

The collection framework (Collection Framework) generally refers to several classes and interfaces of java.util packages. Such as Collection, List, ArrayList, LinkedList, Vector (auto-growing array), HashSet, HashMap, etc.

The classes in the collection framework mainly encapsulate typical data structures, such as dynamic arrays, linked lists, stacks, collections, hash tables, etc.

The set framework is similar to the tool classes often used in programming, which makes the coding focus on the implementation of the business layer and does not need to implement the relevant details from the bottom-"encapsulation of data structures" and "implementation of typical algorithms".

The difference between quick failure (fail-fast) and security failure (fail-safe).

Iterator's security failure is based on copying the underlying collection, so it is not affected by source collection modifications. All collection classes under the util package fail quickly, and all classes under the util.concurren package fail securely.

These are all the contents of this article entitled "what are the common basic knowledge questions of Java". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report