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.
(More interview question recommendations: java interview questions and answers)
2. Does Java have goto?
Reserved words in java are not used in java now.
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 If 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 jump 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 of the 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 don’t usually use labels. Instead, I allow the results of the outer loop conditional expression to be controlled by the inner loop body code. For example, you want 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; } } }
(Recommended study: java introductory tutorial)
5. Can the switch statement act on byte, can it act on long, and can it act on String Above?
In switch(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 wrapper type. Due to byte, short , 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.
It is wrong to say whether the switch statement can be used on String. This writing method is already supported after Java 1.7!
6. short s1= 1; s1 = (s1 1 is int type, and the left side of the equal sign is 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 s1 1 will automatically promote the type of expression during operation, the result is int type, and then assigned to short When type s1, the compiler will report an error requiring a type cast.
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-encoded character set contains Chinese characters, so , of course Chinese characters can be stored in char type 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 variables of type char also occupy two bytes.
8. Use the most efficient method to calculate what is 2 multiplied by 8?
2<< 3, (left shift by three places) Because shifting a number to the left by n places, It is equivalent to multiplying 2 to the nth power. Then, when multiplying a number by 8, you only need to shift it to the left by 3 bits. Bit operations directly supported by the CPU are the most efficient. Therefore, what is the most efficient number of 2 multiplied by 8? The method 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!");
When someone defines the parameters of a method, they may want to use the following form to prevent the method from modifying the parameter object passed in:
public void method(final StringBuffer param){ }
Actually, this is not possible, and it can still be added inside the method. Use the following code to modify the parameter object:
param.append("a");
(Learning video recommendation: java course)
10. What is the difference between static variables and instance variables?
在語法定義上的區(qū)別:靜態(tài)變量前要加static關(guān)鍵字,而實(shí)例變量前則不加。
在程序運(yùn)行時(shí)的區(qū)別:實(shí)例變量屬于某個(gè)對(duì)象的屬性,必須創(chuàng)建了實(shí)例對(duì)象,其中的實(shí)例變量才會(huì)被分配空間,才能使用這個(gè)實(shí)例變量。靜態(tài)變量不屬于某個(gè)實(shí)例對(duì)象,而是屬于類,所以也稱為類變量,只要程序加載了類的字節(jié)碼,不用創(chuàng)建任何實(shí)例對(duì)象,靜態(tài)變量就會(huì)被分配空間,靜態(tài)變量就可以被使用了??傊?,實(shí)例變量必須創(chuàng)建對(duì)象后才可以通過這個(gè)對(duì)象來使用,靜態(tài)變量則可以直接使用類名來引用。
例如,對(duì)于下面的程序,無論創(chuàng)建多少個(gè)實(shí)例對(duì)象,永遠(yuǎn)都只分配了一個(gè)staticVar變量,并且每創(chuàng)建一個(gè)實(shí)例對(duì)象,這個(gè)staticVar就會(huì)加1;但是,每創(chuàng)建一個(gè)實(shí)例對(duì)象,就會(huì)分配一個(gè)instanceVar,即可能分配多個(gè)instanceVar,并且每個(gè)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 Java basic interview questions (1). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa
