Home Java JavaInterview questions Collection of classic Java interview questions (1)

Collection of classic Java interview questions (1)

Jul 02, 2020 pm 04:30 PM
java Interview questions

Collection of classic Java interview questions (1)

##1. The difference between & and &&

(Recommended study:

java interview questions )

& operator has two uses:

(1) bitwise AND;

(2) logical AND.

The&& operator is a short-circuit AND (or concise AND) operation. The difference between logical AND and short-circuit AND is very huge. Although both require the Boolean values ​​on the left and right sides of the operator to be true, the value of the entire expression is true.

&& is called a short-circuit operation because if the value of the expression on the left of && is false, the expression on the right will be directly short-circuited and no operation will be performed. Many times we may need to use && instead of &.

For example, when verifying user login, it is determined that the username is not null and not an empty string. It should be written as username != null &&!username.equals(""). The order of the two cannot be exchanged, let alone used. & operator, because if the first condition is not true, the equals comparison of strings cannot be performed at all, otherwise a NullPointerException exception will be generated.

2. When using the final keyword to modify a variable, does it mean that the reference cannot be changed or the referenced object cannot be changed?

When using the final keyword to modify a variable, it means that the reference variable cannot be changed, but the content of the object pointed to by the reference variable can still be changed.

Example:

public class Test10 {
// final修饰基本类型的变量
public static final char CHAR = '中';
// final修饰引用类型的变量
public static final StringBuffer a = new StringBuffer("StringBuffer");
public static void main(String[] args) {
// 编译报错,引用不能变
// a = new StringBuffer("hehe");
// 引用变量所指向的对象中的内容还是可以改变的
a.append("xxx");
}
public static int method1(final int i) {
// i = i + 1;// 编译报错,因为final修饰的是基本类型的变量
return i;
}
// 有人在定义方法的参数(引用变量)时,可能想采用如下的形式来阻止方法内部修改传进来的参数对象,
// 实际上,这是办不到的,在该方法内部任然可以增加如下代码来修改参数对象
public static void method2(final StringBuffer buffer) {
buffer.append("buffer");// 编译通过,因为final修饰的是引用类型的变量
}
}

3. What is the difference between static variables and instance variables?

Syntax difference: static variables need to be modified with the static keyword, but instance variables do not.

The difference when the program is running: static variables are subordinate to classes, and instance variables are subordinate to objects.

Instance variables must create an instance object, and the instance variables in it will be allocated space before this instance variable can be used;

Static variables are category quantities, as long as the program loads the bytes of the class code, the static variable will be allocated space and can be used.

To sum up, instance variables must be used through this object after creating an object, and static variables can be referenced directly using the class name.

Note: The use of (static) static variables also has limitations. Non-static methods and variables in the class cannot be called in a static method. There is only one variable in the memory after the class is loaded. A memory space that can be shared by all instance objects of a class.

4. Is it possible to issue a call to a non-static method from within a static method?

Can't.

Because non-static methods are associated with objects, an object must be created before method calls can be made on the object. When calling static methods, there is no need to create an object and can be called directly.

In other words, when a static method is called, no instance object may have been created. If a call to a non-static method is issued from a static method, which object is the non-static method associated with? What about? This logic cannot be established, so a static method internally issues a call to a non-static method.

5. What is the difference between "==" and equals methods? The

== operator is specifically used to compare whether the values ​​of two variables are the same, that is, to compare whether the values ​​stored in the memory corresponding to the variables are the same. If you want to compare two basic types of data or two reference variables for equality, you can only use the == operator.

The equals method is used to compare whether the contents of two independent objects are the same, just like comparing whether two books are the same. The two objects it compares are independent.

Code example:

String a = new String("AA");
String b = new String("AA");
System.out.println(a==b);
System.out.println(a.equals(b));

Two new statements create two objects, and then use two variables a and b to point to one of the objects respectively. These are two different objects. They The first addresses of are different, that is, the values ​​stored in a and b are different, so the expression a==b will return false. The contents of the two objects are the same, so a,equals(b) returns true.

Note: String comparisons basically use the equals method.

If a class does not have its own defined equals method, then it will inherit the equals method of the Object class. The implementation code of the Object class is as follows:

boolean equals(Object o)
{
return this==o;
}

This means that if a class does not have its own defined equals method The equals method, its default equals method, is equivalent to using the == operator, that is, comparing the objects pointed to by the two variables to the same object. At this time, using equals and == will get the same result. If you want to write a class that can compare whether the contents of two instance objects are the same, you need to override the equals method.

The above is the detailed content of Collection of classic Java interview questions (1). 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