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

Home Java JavaBase Introduction to several common errors in Java

Introduction to several common errors in Java

Dec 23, 2019 pm 03:43 PM
java

Introduction to several common errors in Java

Common java errors:

1. Null pointer error

In the use of java arrays, sometimes it is necessary to modify the elements in the string array comparing. Then when the element is not null, the program will run normally; however, once the compared element is null, a null pointer error will occur in the program.

Solution: Add protection and make a judgment when the element is not null.

public static void main(Sring[] args){
  String [] sums = "adfafA";
  for(int i=0;i<sums.length;i++){
    if(sums[]!=null && sums[i].equals(sr)){
      System.out.println("找到元素"+sums[i]);
      break;
    }
  }
}

2. Data precision range and type conversion

There are 4 basic types of data in Java:

Integer type: -1 2 3 4 ……

Floating point type: float 1.3f; double 3.2 3.5d (unspecified type, default highest precision)

Character type: Unicode encoding, 2 bytes

Boolean type: The precision ranges of the four basic types of data, true and false

, are different and are improved step by step.

If you do not pay attention to the precision range when using data types, data overflow will occur, resulting in calculation errors.

Among the four basic types, integer, floating-point and character data can be converted to each other.

The conversion rules are as follows:

①Invisible conversion: Data values ??with small precision are assigned to values ??with high precision and can be automatically converted. (Low-level to high-level)

②Forced conversion: data values ??with a large range, (high-level to low-level)

③Operation automatic promotion rules: During operation, it is automatically converted to a high-precision data type.

3. The use of three types of loops

①for loop: It is a loop with a limited number of times. Before the loop, the number of loops is specified.

for(表達式;表達式;表達式){
        循環(huán)體
 }

break statement: After execution, jump out of the loop immediately, do not execute subsequent statements, and end all loops.

continue statement: After execution, immediately jump out of the current word loop and re-judge whether the condition continues to loop.

②While loop statement: suitable for loops of unknown number of times.

while(條件表達式){
  語句
 };

③do-While loop: It is also a loop of unknown number of times. The order must be executed at least once before making a judgment. If while is true, continue the loop, otherwise, end the loop.

do {
 語句
 }while(條件表達式);

4. Copy string multiple times

An error that cannot be found by testing is generating multiple copies of an immutable object. An immutable object cannot be changed, so there is no need to copy it. The most commonly used immutable object is String.

If you must change the contents of a String object, you should use StringBuffer. The following code will work fine:

String s = new String ("Text here");

However, this code has poor performance and is unnecessarily complex. You can also rewrite the above code in the following way:

String temp = "Text here";
String s = new String (temp);

But this code contains additional String, which is not completely necessary. The better code is:

String s = "Text here";

5. There is no object returned by clone.

Encapsulation is an important concept in object-oriented programming. Unfortunately, Java makes it easy to accidentally break encapsulation - Java allows returning references to private data. The following code reveals this:

import java.awt.Dimension;
  /***Example class.The x and y values should never*be negative.*/
  public class Example{
  private Dimension d = new Dimension (0, 0);
  public Example (){ }
  /*** Set height and width. Both height and width must be nonnegative * or an exception is thrown.*/
  public synchronized void setValues (int height,int width) throws IllegalArgumentException{
  if (height <0 || width <0)
  throw new IllegalArgumentException();
  d.height = height;
  d.width = width;
  }
  public synchronized Dimension getValues(){
  // Ooops! Breaks encapsulation
  return d;
  }
  }

The Example class guarantees that the height and width values ??it stores are always non-negative. Trying to use the setValues() method to set negative values ??will trigger an exception. Unfortunately, since getValues() returns a reference to d, not a copy of d, you can write destructive code like this:

  Example ex = new Example();
  Dimension d = ex.getValues();
  d.height = -5;
  d.width = -10;

Now, the Example object has a negative value! If the call to getValues() If the user never sets the width and height values ??of the returned Dimension object, it is impossible to detect such errors by testing alone.

Unfortunately, over time, client code may change the value of the returned Dimension object. At this time, tracing the source of the error is tedious and time-consuming, especially in a multi-threaded environment. .

A better way is to let getValues() return a copy:

  public synchronized Dimension getValues(){
  return new Dimension (d.x, d.y);
  }

6. Copy the wrong data

Sometimes programmers know that they must return a copy, but they don’t. Be careful of copying the wrong data. Since only part of the data copy work has been done, the following code deviates from the programmer's intention:

import java.awt.Dimension;
  /*** Example class. The height and width values should never * be
  negative. */
  public class Example{
  static final public int TOTAL_VALUES = 10;
  private Dimension[] d = new Dimension[TOTAL_VALUES];
  public Example (){ }
  /*** Set height and width. Both height and width must be nonnegative * or an exception will be thrown. */
  public synchronized void setValues (int index, int height, int width) throws IllegalArgumentException{
  if (height <0 || width <0)
  throw new IllegalArgumentException();
  if (d[index] == null)
  d[index] = new Dimension();
  d[index].height = height;
  d[index].width = width;
  }
  public synchronized Dimension[] getValues()
  throws CloneNotSupportedException{
  return (Dimension[])d.clone();
  }
  }

The problem here is that the getValues() method only clones the array, but does not clone the Dimension object contained in the array. , Therefore, although the caller cannot change the internal array so that its elements point to different Dimension objects, the caller can change the contents of the internal array elements (that is, the Dimension object). A better version of the method getValues() is:

 public synchronized Dimension[] getValues() throws CloneNotSupportedException{
  Dimension[] copy = (Dimension[])d.clone();
  for (int i = 0; i
  // NOTE: Dimension isn’t cloneable.
  if (d != null)
  copy[i] = new Dimension (d[i].height, d[i].width);
  }
  return copy;
  }

Similar mistakes will be made when cloning multi-dimensional arrays of atomic type data. Atomic types include int, float, etc. It is correct to simply clone a one-dimensional array of type int, as shown below:

 public void store (int[] data) throws CloneNotSupportedException{
  this.data = (int[])data.clone();
  // OK
  }

Copying a two-dimensional array of type int is more complicated. Java does not have a two-dimensional array of type int, so a two-dimensional array of type int is actually a one-dimensional array: its type is int[]. Simply cloning an array of type int[][] will make the same mistake as the first version of the getValues() method in the example above, so this should be avoided. The following example demonstrates the incorrect and correct methods when cloning a two-dimensional int array:

public void wrongStore (int[][] data) throws CloneNotSupportedException{
  this.data = (int[][])data.clone(); // Not OK!
  }
  public void rightStore (int[][] data){
  // OK!
  this.data = (int[][])data.clone();
  for (int i = 0; i
  if (data != null)
  this.data[i] = (int[])data[i].clone();
  }
  }

For more java knowledge, please pay attention to the java Basic Tutorial column.

The above is the detailed content of Introduction to several common errors in Java. 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)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

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.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

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

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

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

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles