Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common traps in Java?

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces you what are several common traps in Java, the content is very detailed, interested friends can refer to, hope to be helpful to you.

There are many traps in java that beginners often encounter, including the following

Automatic packing and unpacking

Immutable String

Memory leak

Self-increasing type use

Use "=" for object comparison

Double type calculation

Immutable String

The Java String class is immutable (immutable). This is because the String object is cached in the String pool. The object referenced by the string can be changed, but the string object itself cannot be changed.

Strings are immutable. Once a string is created, the string object cannot be changed later.

Java uses passing by value, not by reference. When you assign a new value to a method, it only modifies the local, rather than calling the original s in the code

Automatic packing and unpacking

Boxing is to automatically convert the basic data type to the wrapper type

Unpacking is to automatically convert the wrapper type to the basic data type.

What are the types of packing and unpacking?

From the figure above, you can see that the basic type of java can be unboxed.

What's wrong with unpacking?

Through an example, the above two programs, the calculation time difference is nearly 10 times, when there is a large number of packing behavior, it will lead to poor program performance.

When the encapsulation type is calculated by = =, +, -, *, /, it will be unpacked automatically to operate on the basic data type. So when doing calculations, use basic data types.

Memory leak

One of the core advantages of Java is the Java garbage collector, which manages object memory on the heap. Whenever an object is not accessible, it is automatically released.

However, a common mistake for novice and experienced programmers is to prevent memory from being freed by allowing access to objects that are no longer in use. This can have a significant adverse impact on the project because memory leaks block resources and degrade application performance. It may even lead to java.lang.OutOfMemoryError.

Common situations are:

Static field declaration. Static field and forget to set it to null after its data is no longer needed

The stream is not closed properly. The Java virtual machine allocates memory for each open connection. Forgetting to close the connection consumes memory. Such connections can be: input stream, database connection, session, etc.

The finalize () method. When we override the finalize () method, finalize () will only be called once before the object memory is reclaimed, with uncertain rows, ensuring that the method will be called, but not that the tasks in the method will be executed. So try to avoid using it. In Java 9, it has been declared as an expired function

Self-increasing type use

Operators in Java are calculated from left to right at the same level, as shown in the case of self-increment

The execution context for the first case is as follows:

1. Stores the previous value of the Operand.

two。 Added value.

3. Returns the previous value

The execution context of the second case is as follows:

1. Added value.

two。 Store the value of the Operand (incremented)

3. Return value

Use "=" for object comparison

Many novice programmers try to compare objects using the "=" operator and get confused when the code doesn't behave as expected. It is important to note that the relational operator "=" is making reference comparisons, which checks whether both objects point to the same location in memory. Using the .equals () method eliminates this problem because it compares values within the object.

Although sometimes the "=" operator gives the expected answer:

What is the reason for this? It is also a string, and the way it is created is different. Why is the gap so big?

String literals in Java language specification: text strings in different classes in the same package represent references to the same String object

If it's not clear, take a look at the two string creation processes.

The first way of new

When you new a string, you do two things. First generate the string object in the heap, and then check to see if there is the string in the constant pool. If so, it doesn't matter. If not, add one to the constant pool.

Second, direct assignment

To create a string in this way, you will first go to the constant pool to find out if there is such a string. If there is a string that points directly to the constant pool, add one to the constant pool first, and then point to it.

The above is a comparison of the two ways.

Comparison of two Integer

Then why is it that 100 is equal to 200? this is because Integer uses caching.

The direct Integer type variables generated at one time in the static block are stored in cache []. For int types between-128and 127, the same Integer type object is returned.

The whole process is that when Integer.class loads (Java virtual machine starts), its internal static block of type IntegerCache begins to execute, instantiating and temporarily storing Integer type objects with values between-128and 127s.

When the auto-boxing int value is between-128and 127, the Integer type object temporarily stored in IntegerCache is returned directly.

Why is Java designing like this? It should be for the sake of efficiency, because automatic boxing is often encountered, especially the automatic boxing of decimal values, and it will be too time-consuming if new is triggered each time and memory is allocated in the heap.

Several other basic types of wrapper classes are also cached

Double type calculation

Double and float in Java are represented internally as binary fractions, so they may not be accurate enough to represent decimal fractions (IEEE standard 754). The calculation of decimal number requires precision and requires the use of java.math.BigDecimal

This is the end of what are the common traps in Java. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 221

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report