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 core Java interview questions?

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

Share

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

This article mainly explains "what are the core interview questions for Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the core Java interview questions"?

01. Please name the important features updated in Java 14

Java 14 was released on March 17, 2020, with key updated features:

Switch expression

Instanceof enhanced expression, preview function

Text block, second preview

Records, preview function

02. Please name the important features updated in Java 13

Java 13 was released on September 17, 2019, with key updated features:

Text blocks, preview function

Switch expression, preview function

Java Socket re-implementation

FileSystems.newFileSystem () method

Support for Unicode 12.1

Improved scalable, low-latency garbage collector to return unused memory

03. Please name the important features updated in Java 12

Java 12 was released on March 19, 2019, with key updated features:

JVM update

File.mismatch () method

Compact digital format

Some methods have been added to the String class, such as indent ()

04. Please name the important features updated in Java 11

Java 11 is the second commercial version after Java 8, and you need to pay if you download Oracle JDK; if you want to continue to use the free version, you need to download Open JDK.

There will be some commercial closed-source features in Oracle JDK that Open JDK does not have.

Important features of the Java 11 update are:

You can run the Java program directly using the java command, and the source code will be compiled and run implicitly.

Some new methods are added to the String class, such as isBlank (), lines (), strip (), and so on.

The Files class adds two new read and write methods, readString () and writeString ().

You can use var as a variable type in Lambda expressions.

05. Please name the important features updated in Java 10

Important features of the Java 10 update are:

Local variable type inference, for example, var list = new ArrayList ();, you can use var as the variable type, and the Java compiler knows that the type of list is the ArrayList of a string.

Enhance java.util.Locale.

Provides a set of default root certificate authorities (CA).

06. Please name the important features updated in Java 9

Important features of the Java 9 update are:

Module system

Immutable factory methods for List, Set and Map

There can be private methods in the interface

Improvement of garbage collector

07. Please name the important features updated in the Java 8 version

Java 8, released in March 2014, is arguably the most important version update since Java 6 and is popular with developers.

Functional programming and Lambda expressions

Stream flow

Java Date Time API

Default and static methods can be used in the interface

I strongly recommend clicking on the link above to read the following to correctly understand these concepts.

08. Please name some important concepts in Java object-oriented programming

Abstract

Encapsulation

Polymorphisms

Inherit

09. What does Java's claim to platform independence mean?

Common operating systems are Windows, Linux, OS-X, so platform independence means that we can run Java programs with the same source code in any operating system, for example, we can write Java programs on Windows, and then run it on Linux.

10. What is JVM?

JVM (Java Virtual Machine) is commonly known as the Java virtual machine. It is called a virtual machine because it does not actually exist. It provides a running environment on which Java bytecodes can be run.

JVM provides the following operations:

Load bytecode

Verify bytecode

Execution bytecode

Provide a runtime environment

JVM defines the following:

Storage area

Class file format

Register group

Garbage collection heap

Fatal error report, etc.

Let's try to understand the internal structure of JVM, which includes a class loader (Class Loader), a runtime data area (Runtime Data Areas), and an execution engine (Excution Engine).

1) Class loader

The class loader is a subsystem of JVM that loads class files. Whenever we run a Java program, it is first loaded by the classloader. There are three built-in classloaders in Java:

Start the class loader (Bootstrap Class-Loader) and load the jar files under the jre/lib package, such as the common rt.jar (including all the class files under the Java standard library, such as the classes under the java.lang package, the classes under the java.net package, the classes under the java.util package, the classes under the java.io package, and the classes under the java.sql package).

Extend the class loader (Extension or Ext Class-Loader) to load the jar file under the jre/lib/ext package.

Apply the class loader (Application or App Clas-Loader) to load the Java class according to the program's classpath (classpath).

In general, Java programmers do not need to interact directly with similar loaders. The default behavior of JVM is sufficient for most situations. However, if you encounter a situation where you need to interact with the classloader, and you don't know much about the mechanism of the classloader, you have to spend a lot of time debugging

ClassNotFoundException, NoClassDefFoundError and other anomalies.

For any class, its uniqueness in JVM needs to be determined by its class loader and the class itself. That is, if the loaders of the two classes are different, even if the two classes come from the same bytecode file, the two classes must not be equal (for example, the Class objects of the two classes are not equals).

Is not a little dizzy, come on, through a simple piece of code to understand.

Public class Test {public static void main (String [] args) {ClassLoader loader = Test.class.getClassLoader (); while (loader! = null) {System.out.println (loader.toString ()); loaderloader = loader.getParent ();}

Each Java class maintains a reference to the class loader that defines it, which can be obtained by the class name .class.getClassLoader (); then the upper class loader of the class loader can be obtained through loader.getParent ().

The output of the above code is as follows:

Sun.misc.Launcher$AppClassLoader@18b4aac2 sun.misc.Launcher$ExtClassLoader@4617c264

The first line output is the Test classloader, the application classloader, which is an instance of the sun.misc.Launcher$AppClassLoader class; the second line output is the extended classloader, which is an instance of the sun.misc.Launcher$ExtClassLoader class. What about starting the classloader?

The upper classloader of the extension classloader is supposed to launch the classloader, but in my version of JDK, the getParent () of the extension classloader returns null. So there's no output.

2) Runtime data area

The runtime data area also contains the following.

The PC register (PC Register), also known as the program counter (Program Counter Register), is a small piece of memory that can be seen as a signal indicator of the bytecode executed by the current thread.

The JVM stack (Java Virtual Machine Stack), like the PC register, the JVM stack is thread private. Each JVM thread has its own JVM stack, which is created at the same time as the thread, and its life cycle is the same as the thread.

Native method stack (Native Method Stack), JVM may use the traditional stack to support the execution of Native methods (methods written in languages other than Java [C]). This stack is the native method stack.

Heap, in JVM, a heap is an area of runtime memory that can be shared by threads, as well as an area of memory allocated to all class instances and data objects.

The method area (Method area), in JVM, the information about the loaded type is stored in the method area. Includes type information (Type Information) and method list (Method Tables). The method area is shared by all threads, so the method to access the method area information must be thread-safe.

The runtime constant pool (Runtime Constant Pool) is the runtime representation of the constant pool for each class or interface, including literal values known to the compiler and references to methods or fields that can only be obtained after run-time parsing. In short, when a method or variable is referenced, JVM runs the constant area to find the actual address of the method or variable in memory.

3) execution engine

The execution engine contains:

Interpreter: reads the byte stream and then executes the instruction. Because it interprets and executes instructions one by one, it can interpret bytecode quickly, but it is slow to execute.

Just-in-time (Just-In-Time,JIT) compiler: just-in-time compiler is used to make up for the shortcomings of the interpreter and improve performance. The execution engine first executes in a way that interprets execution, and then, when appropriate, the compiler compiles the entire bytecode into native code. Then, there is no need for the execution engine to interpret the execution method, it can be executed directly through native code. Executing native code is much faster than interpreting one piece at a time. The compiled code can be executed quickly because the native code is saved in the cache.

11. What's the difference between JDK and JVM?

JDK, an acronym for Java Development Kit, is a software environment for Java developers, including JRE and a set of development tools. It can be divided into the following versions:

Standard Edition (this is what most developers use)

Enterprise edition

Miniature version

JDK contains a proprietary JVM and other resources, such as compiler (javac command), interpreter (java command), and so on, to help Java programmers with their development work.

12. What's the difference between JVM and JRE?

Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and Java binaries and other classes that can execute any program. JRE does not include any development tools such as Java compilers, debuggers, etc.

Which class is the superclass of all classes?

Java.lang.Object is a superclass of all Java classes, and we don't need to inherit it because it is implicitly inherited.

Why doesn't Java support multiple inheritance?

If two classes extends a parent class with a specific method, the method is overridden by two subclasses. Then, if you decide to inherit both subclasses, the compiler cannot recognize which subclass's method you want to call when you call the override method. This is also the famous diamond problem, as shown in the picture below.

When an object that inherits both ClassA and ClassB,ClassC calls methods overloaded in ClassA and ClassB, ClassC does not know whether to call ClassA's method or ClassB's method.

Why isn't Java a pure object-oriented programming language?

Java cannot be said to be a pure object-oriented programming language because Java supports basic data types, such as int, short, long, double, and so on, and although they have their own wrapper types, they are not really objects.

16. What's the difference between path and classpath?

Path is the environment variable that the operating system uses to find executable files. The following path variables, such as Java and Maven, are defined on my computer.

Classpath is for Java and is used to specify the bytecode file path loaded by the Java virtual machine.

17. What is the importance of `main () `method in Java?

Each program needs an entry, and for a Java program, the entry is the main method.

Public static void main (String [] args) {}

The public keyword is another access modifier that declares classes as well as methods and variables (all classes are visible). The main () method must be declared as public.

The static keyword indicates that the variable or method is a static variable or method and can be accessed directly through the class without instantiating the object.

The void keyword is used to specify that the method has no return value.

In addition, the main keyword is the name of the method, and the Java virtual machine looks for this identifier when executing the program; args is the parameter name of the main () method, and its type is a String array, that is, when you use the java command to execute the program, you can pass a string array as a parameter to the main () method.

Java HelloWorld Silence King two Silence King three

The javac command is used to compile the program, the java command is used to execute the program, HelloWorld is the class name of the program, Silent King 2 and Silent King 3 are string arrays separated by spaces, and then you can get the passed parameter values through args [0] and args [1] in the main () method.

Public class HelloWorld {public static void main (String [] args) {if ("Silent King II" .equals (args [0])) {} if ("Silent King three" .equals (args [1])) {}

The main () method is not unique, and there are several other variants, although they may not be common, so you can take a quick look at them.

Second, put the square brackets [] closer to args rather than String:

Public static void main (String [] args) {}

Third, put square brackets [] to the right of the args:

Public static void main (String args []) {}

Fourth, you can also change the array form to the form of variable parameters:

Public static void main (String...args) {}

Fifth, add another modifier, strictfp, to the main () method to emphasize compatibility when dealing with floating point numbers:

Public strictfp static void main (String [] args) {}

You can also add the final keyword or the synchronized keyword to the main () method.

Sixth, you can also add the final keyword to the args parameter:

Public static void main (final String [] args) {}

The seventh, the most complex, adds all the keywords that can be added:

Final static synchronized strictfp void main (final String [] args) {}

Of course, you don't need to write the main () method in the form mentioned above in order to pretend, just use the default form provided by IDE.

18. What's the difference between rewriting (Override) and Overload (Overload) of Java?

Let's take a look at a rewritten code first.

Class LaoWang {public void write () {System.out.println (Lao Wang wrote a copy of the count of Monte Cristo);}} public class XiaoWang extends LaoWang {@ Override public void write () {System.out.println (Xiao Wang wrote a copy of La Traviata);}}

The two overridden methods have the same name and the same number of method parameters, but one method is in the parent class and the other is in the subclass. It is as if the parent class LaoWang has a write () method (no parameter), the method body is to write a "count of Monte Cristo"; the child class XiaoWang rewrites the parent class write () method (no parameter), but the method body is to write a "Camellia Girl".

To write a test code.

Public class OverridingTest {public static void main (String [] args) {LaoWang wang = new XiaoWang (); wang.write ();}}

Guess what the result is?

Xiao Wang wrote a book called La Traviata.

In the above code, we declare a variable wang of type LaoWang. During compilation, the compiler checks whether the LaoWang class contains the write () method, finds that the LaoWang class does, and compiles through. During the run, new takes a XiaoWang object and assigns it to wang. At this time, the Java virtual machine knows that wang refers to a XiaoWang object, so it calls the write () method in the subclass XiaoWang instead of the write () method in the parent class, so the output is "Xiao Wang wrote a book of La Traviata".

Let's take a look at another piece of overloaded code.

Class LaoWang {public void read () {System.out.println ("Lao Wang read a book" the Road to the Advanced Development of Web Stack ");} public void read (String bookname) {System.out.println (" Lao Wang read a book "+ bookname +");}}

The two overloaded methods have the same name, but the number of method parameters is different, and inheritance is not involved, and the two methods are in the same class. It's as if the class LaoWang has two methods, both named read (), but one has parameters (the title of the book) and the other doesn't (only read and write a dead book).

To write a test code.

Public class OverloadingTest {public static void main (String [] args) {LaoWang wang = new LaoWang (); wang.read (); wang.read (Jin Ping Mei);}}

There is no need to guess the result. The type of variable wang is LaoWang,wang.read (), which calls the non-parameter read () method, so the first output is "Lao Wang read a copy of" Web full stack development advanced road "; wang.read (" golden bottle ") calls the parameter read (bookname) method, so the output" Lao Wang read a "Golden bottle". During compilation, the compiler knows that the two read () methods are different because their method signatures (= method name + method parameters) are different.

To sum up briefly:

1) the compiler cannot decide which overridden method to call, because it cannot be judged only by the type of variable and can only be decided at run time; but the compiler can clearly know which overloaded method to call, because the reference type is determined and the number of parameters determines which method to call.

2) Polymorphism is aimed at rewriting, not overloading.

If there are multiple methods with the same name but different parameters in a class, it is called method overloading.

A method override is called when there is a method in the parent class and another method in the subclass that has the same signature (the same method name, the same parameters, and the same modifier). Subclasses can add an @ Override annotation when overriding the parent class method.

19. Can the `main () `method be overloaded?

Yes, there can be multiple methods named "main" in a class:

Public class MainTest {public static void main (String [] args) {System.out.println ("main (String [] args)");} public static void main (String [] args,String arg) {System.out.println ("(String [] args,String arg");}}

But when the class runs, it will only find one entry, public static void main (String [] args).

20. Are there multiple public classes in a Java source file?

You cannot have multiple public classes in a Java source file.

21. What is the package of Java?

In Java, we use package (packages) to group related classes, interfaces, and subpackages. The benefits of this are:

Make related types easier to find

Avoid naming conflicts, such as differences between com.itwanger.Hello and com.itwangsan.Hello

Restrict the visibility of classes through packages and access controllers

You can use the package keyword to define a package name, and note that this line of code must be on the first line of a class. It is strongly recommended that you declare classes in the package and do not default, otherwise you will lose the benefits of the package structure.

Package naming should follow the following rules:

It should be all lowercase letters.

Can contain multiple words, using "." between words. Connect, such as java.lang

The name is determined by the company name or organization name, in reverse order. For example, the domain name of my personal blog is www.itwanger.com, so the package name I created is com.itwanger.xxxx.

Each package or subpackage has its own directory structure on disk, and if the Java file is under the com.itwanger.xxxx package, then the directory structure of the file should be com- > itwanger- > xxxx.

By default, the java.lang package is imported by default, and we do not need to explicitly import any classes under the package.

Package com.cmower.bb; public class PackageTest {public static void main (String [] args) {Boolean.toString (true);}}

The Boolean class belongs to the java.lang package and does not need to be explicitly imported when using it.

What is the access modifier?

Access modifiers are very important to Java, and there are currently four types: public, private, protected, and default (the default).

A class can only be decorated with public or default. You have seen a class decorated with public before. Now let me define a class with default permission modifiers for you to enjoy.

Class Dog {}

Haha, there is actually nothing to appreciate. The default means that this class can be accessed by other classes under the same package; public means that this class can be accessed by all classes under the package.

If you insist on decorating the class with private and protected, the compiler will be angry and disagree.

Private can be used to modify the constructors, fields, and methods of a class and can only be accessed by the current class. Protected can also be used to modify class constructors, fields, and methods, but it has a wider scope of permissions and can be accessed by classes in the same package, or subclasses of the current class.

You can use the following figure to compare the differences between the four permission modifiers:

In the same class, regardless of the permission modifier, you can access the

Under the same package, private decorated cannot be accessed.

Subclasses can access the public and protected decorated

The public modifier faces the world, , and can be accessed everywhere.

What is the final keyword?

When the final keyword modifies a class, it indicates that the class cannot be inherited. For example, the String class is final and cannot be inherited.

When the final keyword modifies a method, it means that the subclass cannot override it.

When the final keyword modifies a variable, it means that the variable can only be assigned once, although the state of the variable can be changed.

For more details on final, please refer to another article I wrote earlier:

I can't believe you don't know how to use the final keyword.

What is the static keyword?

The static keyword can be used to modify class variables to make them global, that is, all objects will share the same variable.

The static keyword can be used to modify a method, which is called a static method, which can only access the static variables of the class and can only call the static methods of the class.

For more details on static, please refer to another article I wrote earlier:

Interviewer: brother, tell me about Java's static keyword.

25. What's the difference between finally and finalize?

Finally is usually used with try-catch blocks, and even if the try-catch block throws an exception, the code in the finally block is executed to release resources created in the try block.

Finalize () is a special method of the Object class that will be called by the garbage collector when the object is being garbage collected. This method can be overridden to release system resources.

26. Can a class be declared as static?

You cannot declare an external class as static, but you can declare an inner class as static-- called a static inner class.

27. What is static import?

If you have to use static variables or static methods of another class in one class, we usually need to import the class first and then use the class name. called in the form of variable / method.

Import java.lang.Math; double test = Math.PI * 5

It can also be imported statically, eliminating the need for class names.

Import static java.lang.Math.PI; double test = PI * 5

However, static imports can easily lead to confusion (variable or method names are prone to conflicts), so it is best to avoid static imports.

28. What is try-with-resources?

Try-with-resources is an automatic resource management statement introduced in Java 7. Before that, we had to close resources manually through try-catch-finally. When we forget to close resources, it is easy to cause memory leaks.

For more details on try-with-resources, please refer to another article I wrote earlier:

I can't believe you're still using try-catch-finally.

29. What is multi-catch?

Another improvement in Java 7 is multi-catch, which catches multiple exceptions in a single catch, which is shorter and clearer when a try block throws multiple similar exceptions.

Catch (IOException | SQLException ex) {logger.error (ex); throw new MyException (ex.getMessage ();}

When there are multiple exceptions, you can use the pipe symbol "|" to separate them.

30. What is a static block?

A static block is a block of code that is executed when a class is loaded into memory by Java ClassLoader. It is commonly used to initialize static variables of a class or to create static resources.

What is an interface?

Interface is a core concept in the Java programming language, which is used not only in JDK source code, but also in Java design patterns, frameworks, and tools. Interface provides a way to implement abstraction in Java to define the behavior conventions of subclasses.

At this point, I believe you have a deeper understanding of "what are the core Java interview questions". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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