Home > Java > Java Basics > body text

Introduction to several common errors in Java

Release: 2019-12-23 15:43:28
Original
4442 people have browsed it

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
Copy after login

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(表达式;表达式;表达式){
        循环体
 }
Copy after login

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(条件表达式){
  语句
 };
Copy after login

③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(条件表达式);
Copy after login

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");
Copy after login

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);
Copy after login

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

String s = "Text here";
Copy after login

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;
  }
  }
Copy after login

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;
Copy after login

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);
  }
Copy after login

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();
  }
  }
Copy after login

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;
  }
Copy after login

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
  }
Copy after login

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();
  }
  }
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!