Home Java JavaInterview questions Common basic Java interview questions

Common basic Java interview questions

Dec 14, 2019 pm 03:06 PM
java

Common basic Java interview questions

What is the difference between JDK and JRE?

JDK: The abbreviation of Java Development Kit, java development tool kit, provides java development environment and running environment.

JRE: The abbreviation of Java Runtime Environment, java runtime environment, provides the required environment for the operation of java. (Recommended study: java common interview questions)

Specifically, JDK actually includes JRE, and also includes the compiler javac that compiles java source code, and also includes many java program debugging and Tools for analysis. To put it simply: if you need to run java programs, you only need to install JRE. If you need to write java programs, you need to install JDK.

== What is the difference between equals and equals?

The effects of == are different for basic types and reference types, as follows:

Basic types: What is compared is whether the values ​​are the same;

Reference type: What is compared is whether the references are the same;

quals is essentially ==, except that String and Integer override the equals method and turn it into a value comparison.

== For basic types, it is a value comparison, for reference types, it is a reference comparison; and equals is a reference comparison by default, but many classes override the equals method, such as String, Integer etc. turns it into a value comparison, so under normal circumstances equals compares whether the values ​​are equal.

If the hashCode() of two objects is the same, equals() must also be true, right?

No, the hashCode() of the two objects is the same, and equals() may not be true.

String str1 = "通话";
String str2 = "重地";
System.out.println(String.format("str1:%d | str2:%d",  str1.hashCode(),str2.hashCode()));
System.out.println(str1.equals(str2));

Result of execution:

str1:1179395 | str2:1179395
false

Code interpretation: Obviously the hashCode() of "call" and "powerful place" are the same, but equals() is false, Because in a hash table, equal hashCode() means that the hash values ​​of two key-value pairs are equal. However, equal hash values ​​do not necessarily mean that the key-value pairs are equal.

What is the role of final in java?

The final modified class is called the final class, and this class cannot be inherited.

Final modified methods cannot be overridden.

Final modified variables are called constants. Constants must be initialized. After initialization, the value cannot be modified.

What is Math.round(-1.5) in java equal to?

is equal to -1.

String is a basic data type?

String does not belong to the basic type. There are 8 basic types: byte, boolean, char, short, int, float, long, double, and String belongs to the object.

What are the classes for operating strings in java? What's the difference between them?

The classes that operate on strings include: String, StringBuffer, and StringBuilder.

The difference between String and StringBuffer and StringBuilder is that String declares an immutable object. Each operation will generate a new String object, and then point the pointer to the new String object, while StringBuffer and StringBuilder can be used in the original object. The operation is performed on the basis of , so it is best not to use String when the content of the string is frequently changed.

The biggest difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe, while StringBuilder is non-thread-safe, but the performance of StringBuilder is higher than StringBuffer, so it is recommended to use StringBuilder in a single-threaded environment and in a multi-threaded environment. It is recommended to use StringBuffer.

String str="i" is the same as String str=new String("i")?

It’s different because the memory allocation method is different. String str="i", the Java virtual machine will allocate it to the constant pool; and String str=new String("i") will be allocated to the heap memory.

How to reverse a string?

Use the reverse() method of StringBuilder or stringBuffer.

Sample code:

// StringBuffer reverse
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("abcdefg");
System.out.println(stringBuffer.reverse()); // gfedcba
// StringBuilder reverse
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("abcdefg");
System.out.println(stringBuilder.reverse()); // gfedcba

What are the common methods of the String class?

indexOf():返回指定字符的索引。
charAt():返回指定索引处的字符。
replace():字符串替换。
trim():去除字符串两端空白。
split():分割字符串,返回一个分割后的字符串数组。
getBytes():返回字符串的 byte 类型数组。
length():返回字符串长度。
toLowerCase():将字符串转成小写字母。
toUpperCase():将字符串转成大写字符。
substring():截取字符串。
equals():字符串比较。

Do abstract classes have to have abstract methods?

No, abstract classes do not necessarily have to have abstract methods.

Sample code:

abstract class Cat {
    public static void sayHi() {
        System.out.println("hi~");
    }
}

In the above code, the abstract class does not have abstract methods but it can run normally.

What are the differences between ordinary classes and abstract classes?

Ordinary classes cannot contain abstract methods, while abstract classes can contain abstract methods.

Abstract classes cannot be instantiated directly, but ordinary classes can be instantiated directly.

Can abstract classes be modified with final?

No, defining an abstract class is for other classes to inherit. If it is defined as final, the class cannot be inherited, which will cause conflicts with each other, so final cannot modify the abstract class, as shown in the figure below , the editor will also prompt an error message:

Common basic Java interview questions

What is the difference between an interface and an abstract class?

Implementation: Subclasses of abstract classes use extends to inherit; interfaces must use implements to implement the interface.

构造函数:抽象类可以有构造函数;接口不能有。

main 方法:抽象类可以有 main 方法,并且我们能运行它;接口不能有 main 方法。

实现数量:类可以实现很多个接口;但是只能继承一个抽象类。

访问修饰符:接口中的方法默认使用 public 修饰;抽象类中的方法可以是任意访问修饰符。

java 中 IO 流分为几种?

按功能来分:输入流(input)、输出流(output)。

按类型来分:字节流和字符流。

字节流和字符流的区别是:字节流按 8 位传输以字节为单位输入输出数据,字符流按 16 位传输以字符为单位输入输出数据。

BIO、NIO、AIO 有什么区别?

BIO:Block IO 同步阻塞式 IO,就是我们平常使用的传统 IO,它的特点是模式简单使用方便,并发处理能力低。

NIO:New IO 同步非阻塞 IO,是传统 IO 的升级,客户端和服务器端通过 Channel(通道)通讯,实现了多路复用。

AIO:Asynchronous IO 是 NIO 的升级,也叫 NIO2,实现了异步非堵塞 IO ,异步 IO 的操作基于事件和回调机制。

Files的常用方法都有哪些?

Files.exists():检测文件路径是否存在。
Files.createFile():创建文件。
Files.createDirectory():创建文件夹。
Files.delete():删除一个文件或目录。
Files.copy():复制文件。
Files.move():移动文件。
Files.size():查看文件个数。
Files.read():读取文件。
Files.write():写入文件。

The above is the detailed content of Common basic Java interview questions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Java Persistence with Spring Data JPA and Hibernate Java Persistence with Spring Data JPA and Hibernate Aug 22, 2025 am 07:52 AM

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

LOL Game Settings Not Saving After Closing [FIXED] LOL Game Settings Not Saving After Closing [FIXED] Aug 24, 2025 am 03:17 AM

IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.

How to use the Pattern and Matcher classes in Java? How to use the Pattern and Matcher classes in Java? Aug 22, 2025 am 09:57 AM

The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient

Edit bookmarks in chrome Edit bookmarks in chrome Aug 27, 2025 am 12:03 AM

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.

'Java is not recognized' Error in CMD [3 Simple Steps] 'Java is not recognized' Error in CMD [3 Simple Steps] Aug 23, 2025 am 01:50 AM

IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.

See all articles