Home Java JavaInterview questions Basic Java interview questions (1)

Basic Java interview questions (1)

Nov 30, 2019 pm 01:25 PM
java

Basic Java interview questions (1)

#1. Can a ".java" source file include multiple classes (not internal classes)? What are the restrictions?

There can be multiple classes, but there can only be one public class, and the public class name must be consistent with the file name. (Recommended study: java interview questions)

2. Does Java have goto?

is a reserved word in java, but it is not in java now use.

3. Talk about the difference between & and &&.

& and && can be used as logical AND operators, indicating logical AND (and). When the results of the expressions on both sides of the operator are true, the entire operation result is true. Otherwise, as long as one of the parties is false, the result is false.

&& also has the function of short-circuiting, that is, if the first expression is false, the second expression will no longer be evaluated, for example, for if(str!= null&& !str.equals( s)) expression, when str is null, the following expression will not be executed, so NullPointerException will not occur

If && is changed to &, NullPointerException will be thrown. If(x==33 & y>0) y will grow, If(x==33 && y>0) will not grow

& can also be used as a bit operator, when the & operator on both sides When the expression is not of boolean type, & represents a bitwise AND operation. We usually use 0x0f to perform the & operation with an integer to obtain the lowest 4 bits of the integer. For example, the result of 0x31 & 0x0f is 0x01.

4. How to get out of the current multiple nested loops in JAVA?

In Java, if you want to break out of multiple loops, you can define a label before the outer loop statement, and then use the break statement with the label in the code of the inner loop body to jump out. Outer loop.

For example:

for(int i=0;i<10;i++){
   for(intj=0;j<10;j++){
       System.out.println(“i=” + i + “,j=” + j);
       if(j == 5) break ok;
   }
}

In addition, I personally do not usually use labels, but let the results of the outer loop conditional expression be affected by the inner layer. Control of the loop body code, for example, to find a number in a two-dimensional array.

int arr[][] ={{1,2,3},{4,5,6,7},{9}};
boolean found = false;
for(int i=0;i<arr.length&&!found;i++)       {
        for(intj=0;j<arr[i].length;j++){
              System.out.println(“i=” + i + “,j=” + j);
              if(arr[i][j] ==5) {
                      found =true;
                      break;
              }
        }
}

5. Can the switch statement act on byte, long, or String?

In switch ( In e), e can only be an integer expression or enumeration constant (larger font). The integer expression can be the int basic type or the Integer packaging type. Since byte, short, and char can be implicitly converted to int, so , these types and packaging types of these types are also possible.

Obviously, neither long nor String types conform to the syntax of switch and cannot be implicitly converted to int type, so they cannot be used in switch statements. (After java1.7, it can already be used on String type, as well as char byte short int and their packaging classes.)

#6, short s1= 1; s1 = (s1 1 is int type, and the left side of the equal sign is the short type, so it needs to be forced) 1 1; What’s wrong? short s1 = 1; s1 = 1; What’s wrong? (Nothing wrong)

For short s1= 1; s1 = s1 1; Since the type of expression is automatically promoted when s1 1 is operated, the result is of type int. When assigned to short type s1, the compiler will report an error that requires cast type.

For short s1= 1; s1 = 1; since = is an operator specified in the java language, the java compiler will perform special processing on it, so it can be compiled correctly.

7. Can a Chinese character be stored in a char variable? Why?

The char variable is used to store Unicode-encoded characters. The unicode encoding character set contains Chinese characters, so of course Chinese characters can be stored in char variables. However, if a special Chinese character is not included in the unicode encoding character set, then the special Chinese character cannot be stored in this char variable.

Additional explanation: Unicode encoding occupies two bytes, so the char type variable also occupies two bytes.

8. Use the most efficient method to calculate what is 2 times 8?

2<< 3, (shift three places to the left) because Shifting a number to the left by n bits is equivalent to multiplying 2 to the nth power. Then, to multiply a number by 8, you only need to shift it to the left by 3 bits. Bit operations are directly supported by the CPU and are the most efficient. Therefore, The most efficient way to find out what is 2 times 8 is 2<<3.

9. When using the final keyword to modify a variable, does 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. For example, for the following statement:

 finalStringBuffer a=new StringBuffer("immutable");

Executing the following statement will report a compile-time error:

a=new StringBuffer("");

However, executing the following statement will compile:

a.append(" broken!");

Someone is defining a method When passing parameters, you may want to use the following form to prevent the method from modifying the passed parameter object:

public void method(final  StringBuffer param){
}

Actually, this is not possible. You can still add the following code inside the method to modify the parameter object. :

 param.append("a");

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

在语法定义上的区别:静态变量前要加static关键字,而实例变量前则不加。

在程序运行时的区别:实例变量属于某个对象的属性,必须创建了实例对象,其中的实例变量才会被分配空间,才能使用这个实例变量。

静态变量不属于某个实例对象,而是属于类,所以也称为类变量,只要程序加载了类的字节码,不用创建任何实例对象,静态变量就会被分配空间,静态变量就可以被使用了。

总之,实例变量必须创建对象后才可以通过这个对象来使用,静态变量则可以直接使用类名来引用。

例如,对于下面的程序,无论创建多少个实例对象,永远都只分配了一个staticVar变量,并且每创建一个实例对象,这个staticVar就会加1;但是,每创建一个实例对象,就会分配一个instanceVar,即可能分配多个instanceVar,并且每个instanceVar的值都只自加了1次。

public class VariantTest{
        publicstatic int staticVar = 0;
        publicint instanceVar = 0;
        publicVariantTest(){
              staticVar++;
              instanceVar++;
              System.out.println(staticVar +instanceVar);
        }
}

The above is the detailed content of Basic 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