国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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?

在語法定義上的區(qū)別:靜態(tài)變量前要加static關(guān)鍵字,而實例變量前則不加。

在程序運行時的區(qū)別:實例變量屬于某個對象的屬性,必須創(chuàng)建了實例對象,其中的實例變量才會被分配空間,才能使用這個實例變量。

靜態(tài)變量不屬于某個實例對象,而是屬于類,所以也稱為類變量,只要程序加載了類的字節(jié)碼,不用創(chuàng)建任何實例對象,靜態(tài)變量就會被分配空間,靜態(tài)變量就可以被使用了。

總之,實例變量必須創(chuàng)建對象后才可以通過這個對象來使用,靜態(tài)變量則可以直接使用類名來引用。

例如,對于下面的程序,無論創(chuàng)建多少個實例對象,永遠都只分配了一個staticVar變量,并且每創(chuàng)建一個實例對象,這個staticVar就會加1;但是,每創(chuàng)建一個實例對象,就會分配一個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)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Java Optional example Java Optional example Jul 12, 2025 am 02:55 AM

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

How to fix java.io.NotSerializableException? How to fix java.io.NotSerializableException? Jul 12, 2025 am 03:07 AM

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

Java method references explained Java method references explained Jul 12, 2025 am 02:59 AM

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

How to parse JSON in Java? How to parse JSON in Java? Jul 11, 2025 am 02:18 AM

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.

Outlook shortcut for new email Outlook shortcut for new email Jul 11, 2025 am 03:25 AM

How to quickly create new emails in Outlook is as follows: 1. The desktop version uses the shortcut key Ctrl Shift M to directly pop up a new email window; 2. The web version can create new emails in one-click by creating a bookmark containing JavaScript (such as javascript:document.querySelector("divrole='button'").click()); 3. Use browser plug-ins (such as Vimium, CrxMouseGestures) to trigger the "New Mail" button; 4. Windows users can also select "New Mail" by right-clicking the Outlook icon of the taskbar

See all articles