• 周六. 1 月 11th, 2025 4:49:23 AM

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Sorting out the basic questions of Java interview (1)

King Wang

1 月 3, 2022

1. Scope public、private、protected、 And the difference when not writing

Scope The current class same package Descendant other package
public
protected x
friendly x x
private x x x

If you don’t write it, it will default to friendly

2.Static Nested Class and Inner Class Different

Nested Class It’s usually C++ That’s what I’m saying ,Inner Class It’s usually Java That’s what I’m saying .Java Inner class and C++ The biggest difference between nested classes is whether there are references pointing to the outside . notes : Static inner class (Inner Class) signify :

  • Create a static Objects of inner classes , You don’t need an external class object
  • Not from a static An object of an inner class accesses an external class object

3.& and && The difference between

& It’s a bit operator , Represent bitwise and operation ,&& Is a logical operator , Representation logic and (and)

4.Collection and Collections The difference between

  • Collection Is the parent interface of a collection class , The interfaces that inherit it are mainly Set and List
  • Collections Is a help class for collection classes , He provides a series of static methods for searching various collections 、 Sort 、 Thread safety and other operations

5. When will it be used assert

assertion( Assertion ) It is a common debugging method in software development , This mechanism is supported in many development languages . In implementation ,assertion It’s a statement in a program , It’s for one boolean Expression to check , A proper program must guarantee this boolean The value of the expression is true;
If the value is false, Indicates that the program is already in an incorrect state , The system will give a warning or exit . Generally speaking ,assertion Used to ensure that the program is basic 、 Critical correctness .assertion Checks are usually turned on during development and testing . To improve performance , After the software is released ,assertion The check is usually off

6.String s=new String(“abc”) Will create a few String Object

Two , One is a string object abc, The other is the reference object s

7. How to find the length of array or string

There is no length() This method , But there are length This attribute . and String There are length() This method .

8.Overload and Override The difference between ,Overload The return value type of the method

  • Method rewrite Override And overloading Overload It’s all Java Different manifestations of polymorphism .
  • rewrite Override It is a manifestation of polymorphism between parents and children , heavy load Overload Is a manifestation of polymorphism in a class .
  • If a method defined in a subclass has the same name and parameters as the method of its parent class , Then the method is overridden (Override). When subclass objects use this method , The definition in the subclass… Will be called , For subclasses , The definition in the parent class is ” shielding “. If more than one method with the same name is defined in a class , They may have different parameter numbers or types or even parameter order , This is called method overloading (Overload).Overload The return value type of the method of is unlimited , You can change .

9. How to distinguish between Set Are the elements in it repeated , Yes, it is == still equals()

Set The elements in are not repeatable , It can be used iterator() Method to distinguish repetition from non repetition .equals() It’s about reading two Set Whether it is equal or not
equals() and == Method to determine whether the reference value points to the same object equals() Overridden in class , So when the content and type of two separate objects match , Return true

10 What are the common anomalies

Common runtime exceptions are as follows :

ArithmeticException, ArrayStoreException,
BufferOverflowException, BufferUnderflowException,
ClassCastException,ConcurrentModificationException,
EmptyStackException,UnsupportedOperationException
IllegalArgumentException, IllegalMonitorStateException,
IllegalPathStateException, IllegalStateException,
ImagingOpException, IndexOutOfBoundsException,
MissingResourceException, NegativeArraySizeException,
NoSuchElementException, NullPointerException,
ProfileDataException, ProviderException,
RasterFormatException, SecurityException,
SystemException, UndeclaredThrowableException,

11.abstract class and interface

  • An interface is a variant of an abstract class , All methods in the interface are abstract , The abstract class is just a kind of method that can be declared and not implemented .
  • Interfaces can inherit more , You can’t abstract classes
  • The method defined in the interface is not implementable , And the part of the abstract class can implement
  • The basic data type in the interface must be static Modified , And abstract classes are not
  • Interfaces cannot contain static code blocks and static methods , And abstract classes can contain

in addition , Abstract classes are more functional than interfaces , But defining abstract classes is expensive . Although the interface is a little poor in function , But it’s just a description of an action , And you can implement multiple interfaces in a class , therefore , It helps to reduce the complexity of design .

12. Interface inheritable or not ? Whether abstract class can be implemented (implements) Interface ? Whether abstract class can inherit entity class (concrete class)

Interface can inherit interface . Abstract classes can implement (implements) Interface , Abstractions can inherit entity classes , But the premise is that entity classes must have explicit constructors

13. Can I inherit String

String Class is final Class cannot be inherited

14.try {} There’s one in it return sentence , So it’s right here try After finally{} Inside code Will it be carried out , When to execute

Will execute , stay return Pre execution

15. When an object is passed as a parameter to a method , This method changes the properties of this object , And return the changed result , So is it value passing or reference passing

It’s worth passing on .Java Only values pass parameters in . When an object instance is passed to a method as a parameter , The value of the parameter is a reference to the object . The contents of the object can be changed in the called method , But references to objects never change

16.ArrayList and Vector The difference between ,HashMap and Hashtable The difference between

Just ArrayList And Vector Mainly from two aspects .

  • Synchronicity :Vector It’s thread safe , So it’s synchronous , and ArrayList It’s a line program that’s not safe , It’s not synchronous
  • Data growth : When it needs to grow ,Vector The default growth is the original one , and ArrayList But half of the original

Just HashMap and HashTable Mainly in terms of aspects

  • Historical reasons :Hashtable It’s based on the old Dictionary Class ,HashMap yes Java 1.2 Imported Map An implementation of the interface
    • Synchronicity :Hashtable It’s thread safe , So it’s synchronous , and HashMap It’s not thread safe , It’s not synchronous
  • value : Only HashMap You can use null as the entry of a table key or value

17.GC What is it? , Why is there GC

GC It’s garbage collection (Gabage Collection), Memory processing is a problem for programmers , Forgetting or wrong memory recycling can lead to program or system instability or even crash ,Java Provided GC The function can automatically monitor whether the object is beyond the scope to achieve the purpose of automatically reclaiming memory ,Java The language does not provide a display operation to release allocated memory .

18. JAVA Medium Collection FrameWork

Collection
├List
│├LinkedList
│├ArrayList
│└Vector
│ └Stack
└Set
Map
├Hashtable
├HashMap
└WeakHashMap
Collection Is the most basic set interface , One Collection Representing a group Object, namely Collection The elements of (Elements), and Map Provide key To value Mapping

19.String And StringBuffer The difference between

String The length of is immutable , and StringBuffer The length of is variable . If you manipulate the contents of a string frequently , Especially when the content needs to be modified , So use StringBuffer, If at last you need String, You can use StringBuffer Of toString() Method

20.final, finally, finalize The difference between

final Modifier ( keyword ) If a class is declared as final, This means that it can no longer derive new subclasses , Cannot be inherited as a parent class . So a class cannot be declared as abstract Of , It was declared that “final` Of .

Declare a variable or method as final, It can guarantee that they will not be changed in use .

Be declared final Must be declared with an initial value , And in the future reference can only read , Do not modify the .

Be declared final The same can only be used , Cannot overload

finally Is provided during exception handling finally Block to perform any cleanup operations . If an exception is thrown , So the matching catch Clause will execute , Then control will enter finally block ( If you have any )

finalize Method name .Java Technology allows the use of finalize() Method do the necessary cleanup before the garbage collector clears the object from memory . This method is used by the garbage collector to determine that the object is not referenced
This object is called with time . It’s in Object Class , So all classes inherit it . Subclass coverage finalize() Method to clean up system resources or perform other cleanup work .finalize() Method is called on the object before it is deleted by the garbage collector .

21. Object oriented features

  • abstract : Abstraction is to ignore 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 . Abstraction does not intend to understand the whole problem , It’s just a part of it . There are two aspects of abstraction , One is process abstraction , Second, data abstraction .

  • Inherit : Inheritance is a hierarchical model of join classes , And to allow and encourage the reuse of classes , It provides a way to articulate commonality . A new class of object can be derived from an existing class , This process is called class inheritance . The new class inherits the properties of the original class , The new class is called the derived class of the original class ( Subclass ), The original class is called the base class of the new class ( 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 .

  • encapsulation : Encapsulation is the encircling of processes and data , Access to data can only be through defined interfaces . Object oriented computing starts with this basic concept , That is, the real world can be described as a series of complete autonomy 、 Encapsulated objects , These objects access other objects through a protected interface .

  • polymorphism : Polymorphism means that different objects are allowed to respond to the same message . Polymorphism includes parametric polymorphism and inclusion polymorphism . Polymorphic language is flexible 、 abstract 、 Behavior sharing 、 Advantages of code sharing , It solves the problem of the same name of application function .

    22.int and Integer The difference between

    Java There are two different types : Reference types and primitive types ( Or built-in type ).

    Int yes java Original data type of ,Integer yes java by int Provided encapsulation class .Java A wrapper class is provided for each primitive type , as follows :

    boolean Boolean,
    char Character,
    byte Byte,
    short Short,
    int Integer,
    long Long,
    float Float,
    double Double
    

    The behavior of the reference type is completely different from that of the original type , And it has different semantics .

    Reference types and primitive types have different characteristics and usages , They include : Size and speed issues , What kind of data structure does this type store , The default value specified when the reference type and the original type are used as instance data for a class . The default value of the object reference instance variable is null, The default values of primitive type instance variables are related to their types

    23. What are the similarities and differences between runtime exceptions and general exceptions

    An exception indicates an abnormal state that may occur during program operation , Runtime exception indicates an exception that may be encountered in the normal operation of a virtual machine , Is a common run error .

    java The compiler requires methods to declare that they throw non runtime exceptions that may occur , However, it is not required to declare that an uncollected run must be thrown
    When abnormal .

    24.ArrayList,Vector, LinkedList Storage performance and characteristics of

    ArrayList and Vector All use array to store data , The number of elements in this array is greater than the data actually stored in order to increase and insert elements , They all allow elements to be indexed directly by ordinal , But inserting elements involves memory operations such as array element movement , So index data is fast and insert data is slow ,

    Vector Due to the use of synchronized Method ( Thread safety ), Generally, the performance is better ArrayList Bad ,LinkedList Storage using double linked list , Index data by sequence number needs to be traversed forward or backward , But when inserting data, you only need to record the front and back items of this item , So the insertion speed is faster .

    25.HashMap and Hashtable The difference between

    HashMap yes Hashtable Lightweight implementation of ( Implementation of non thread safety ), They all finished Map Interface , The main difference is that HashMap Allow space (null) Key value (key), Because it’s not thread safe , It may be more efficient than Hashtable.
    Hashtable Allows you to null As a entry Of key perhaps value, and Hashtable Don’t allow .
    HashMap hold Hashtable Of contains The method removes , Change to containsvalue and containsKey. because contains Methods are misleading .
    Hashtable Inherited from Dictionary class , and HashMap yes Java1.2 Imported Map interface An implementation of .
    The biggest difference is ,Hashtable Approach is to Synchronize Of , and HashMap No , Access in multiple threads Hashtable when , No need to synchronize its methods , and HashMap It must be provided with external synchronization .
    Hashtable and HashMap Adopted hash/rehash The algorithm is almost the same , So there’s no big difference in performance .

    26.heap and stack The difference between

    Stack (stack) It’s a linear set , Its operation of adding and deleting elements should be completed in the same paragraph . The stack is processed in a last in, first out fashion . Pile up (heap) It’s a component of the stack

    27.Java Interface and C++ The similarities and differences of virtual classes of

    because Java Multiple inheritance is not supported , It is possible for a class or object to use methods or properties in several classes or objects , The existing single inheritance mechanism can not meet the requirements . Compared with inheritance , Interface has more flexibility , Because there is no implementation code in the interface . When a class implements an interface , This class implements all methods and properties in the interface , And the properties in the interface are all in the default state public static, All methods default to public. A class can implement multiple interfaces .

    28.Java The simple principle and application of exception handling mechanism in

    When JAVA The procedure violated JAVA The semantic rules of ,JAVA The virtual machine will express the error as an exception . Violation of semantic rules is :

    • JAVA Class library built-in semantic check . For example, array subscript is out of bounds , May trigger IndexOutOfBoundsException; visit null When the object of NullPointerException.
    • JAVA Allow programmers to extend this semantic check , Programmers can create their own exceptions , And free to choose when to use throw Keyword threw exception . All the exceptions are java.lang.Thowable Subclasses of .

    29. Advantages and principles of garbage collection . And think about 2 A recycling mechanism

    Java A remarkable feature of language is the introduction of garbage collection mechanism , send c++ The biggest memory management problem for programmers is solved , It makes the Java Programmers no longer need to think about memory management when writing programs . Because of the garbage collection mechanism ,Java Objects in no longer have ” Scope ” The concept of , Only references to objects are available ” Scope “. Garbage collection can effectively prevent memory leakage , Efficient use of available memory .

    The garbage collector usually runs as a separate low-level thread , Unpredictable cleaning and recycling of dead or unused objects in the memory heap , Programmers can’t call the garbage collector to garbage an object or all objects in real time .

    Recycling mechanism Yes Generational replication garbage collection and label garbage collection , Incremental garbage collection .

    30. What collection classes do you know ? The main method ?
    The most common set class is List and Map. List The specific implementation includes ArrayList and Vector, They are variable size lists , More suitable for construction 、 A list of elements that store and manipulate objects of any type . List It is suitable for accessing elements by numerical index .
    Map Provides a more general element storage method . Map Collection classes are used to store element pairs ( Referred to as ” key ” and ” value “), Each of these keys maps to a value .

    31. Describe the JVM load class The principle and mechanism of documents

    JVM The loading of classes in is done by ClassLoader And its subclasses ,Java ClassLoader It’s an important Java Runtime system components . It is responsible for finding and loading the class file’s classes at run time .

    32. What are the sorting methods

    There are ways to sort : Insertion sort ( Direct insert sort 、 Shell Sort ), Exchange sort ( Bubble sort 、 Quick sort ), Selection sort ( Direct selection sorting 、 Heap sort ), Merge sort , Assign sort ( Cases of sorting 、 Radix sorting ) Pseudo code for quick sort .

    33.JAVA How to deal with language exceptions , keyword :throws,throw,try,catch,finally What is the meaning of each of them ? stay try Can an exception be thrown in a block ?

    Java Object oriented method of exception handling , Classify all kinds of exceptions , And provide a good interface . stay Java in , Each exception is an object , It is Throwable An instance of a class or other subclass . When a method has an exception, it throws an exception object , The object contains exception information , The method that calls this object can catch the exception and handle it .Java The exception handling of 5 Key words to achieve :try、catch、throw、throws and finally.

    Generally, it is used try To execute a program , If there is an anomaly , The system will throw (throws) An exception , This can be captured by its type (catch) it , Or last (finally) Handled by the default processor .
    use try To designate a piece to prevent all ” abnormal ” The program . Keep up with the try After the program , It should include a catch Clause to specify what you want to capture ” abnormal ” The type of .

    • throw Statement is used to explicitly throw a ” abnormal “.
    • throws Used to indicate the various kinds that a member function may throw ” abnormal “.
    • Finally To make sure that a piece of code doesn’t matter what happens ” abnormal ” They’re all executing a piece of code .

    34. One “.java” Can multiple classes be included in the source file ( Not an inner class )? What are the limitations ?

    Sure . Only one class name must be the same as the file name .

    35.java What is the mechanism of realizing polymorphism in ?
    Method rewrite Override And overloading Overload yes Java Different manifestations of polymorphism .

    rewrite Override It is a manifestation of polymorphism between parents and children , heavy load Overload Is a manifestation of polymorphism in a class .

    36. What is the basic principle of garbage collector ? Can the garbage collector reclaim memory immediately ? What is the way to inform virtual machine of garbage collection
    about GC Come on , When a programmer creates an object ,GC Start monitoring the address of this object 、 Size and usage . Usually ,GC Using directed graph to record and manage the heap (heap) All objects in . In this way, you can determine which objects are ” Accessible “, Which objects are ” Inaccessible “. When GC Identify some objects as ” Unreachable ” when ,GC It’s our responsibility to reclaim this memory space .

    Sure . Programmers can do it manually System.gc(), notice GC function , however Java Language norms do not guarantee GC It will be carried out .

    37. What is? java serialize , How to achieve java serialize ?

    Serialization is a mechanism for processing object streams , The so-called object flow is to flow the content of the object . Can read and write to the object after convection , You can also transfer the streamed objects between networks .

    Serialization is to solve the problem of reading and writing to the object stream .
    Implementation of serialization : Will need to be serialized class implementation Serializable Interface , There is no way to implement this interface ,implements Serializable Just to mark that the object is serializable , Then use an output stream ( Such as :FileOutputStream) To construct a ObjectOutputStream( Object flow ) object , next , Use ObjectOutputStream Object’s writeObject(Object obj) Method to set the parameter to obj Object write out ( Save its status ), To restore, use input stream .

    38. Can I static Method issued internally static Method call ?

    Can not be , If it contains method(); Object initialization is not guaranteed .

    39. Write clone() When the method is used , There’s usually one line of code , Which line of business

    Clone Default behavior ,super.clone(); He’s responsible for producing the right size of space , And copy… Bit by bit .

    40.List 、Map 、Set Three interfaces , When accessing elements , What are the characteristics of each ?

    • List To hold elements in a particular order , There can be repeating elements .

    • Set Can’t have repeating elements , Internal sorting

    • Map preservation key-value value ,value It’s worth more .

发表回复

StatCounter - Free Web Tracker and Counter