JavaRush /Java Blog /Random EN /Mistakes of beginner java programmers. Part 1
articles
Level 15

Mistakes of beginner java programmers. Part 1

Published in the Random EN group

1. The name of the class is different from the name of the file in which it is stored

All java frameworks I've used, including the Javasoft JDKs, assume that the source code for a class with the public modifier is stored in a file with exactly the same name as the class name and a .java extension. Failure to follow this convention can cause many problems that will show up during compilation.
Mistakes of beginner java programmers.  Part 1 - 1
Beginning students (programmers) often forget about this convention and, for example, set the file name in accordance with the assignment: Lab6.java. Wrong example: File nameLab6.java
public class Airplane extends Vehicle
  Seat pilot;
  public Airplane() {
    pilot = new Seat();
  }
}
Corrected example: FilenameAirplane.java
public class Airplane extends Vehicle
  Seat pilot;
  public Airplane() {
    pilot = new Seat();
  }
}
Please note:the class name is assumed to begin with a capital letter. Operating systems that are case-sensitive in file names may present additional problems, especially for students learning Java on Unix who are accustomed to the DOS file naming system. The class MotorVehicleshould be stored in a file MotorVehicle.java, but not in a motorvehicle.java.

2. Comparison using==

In Java, strings are objects of the class java.lang.String. The operator ==applied to objects checks for equality of references to objects! Sometimes students do not understand the semantics of the operator ==and try to use it to compare strings. Wrong example:
// проверим, equals ли первый аргумент "-a"
if (args[0] == "-a") {
    optionsAll = true;
}
The correct way to compare 2 strings for equality is to use the equals()class method java.lang.String. It returns trueif the strings are the same length and contain the same characters. (Note: actually this does not guarantee equality. In fact, equalsit checks whether 2 strings are equal character by character) Corrected example:
//  проверим, equals ли первый аргумент "-a"
if ("-a".equals(args[0])) {
    optionsAll = true;
}
This error is stupid, because in fact the Java code turns out to be syntactically correct, but in the end it does not work as expected. Some students also try to use comparison operators >and instead of class <=methods . This error is easier to detect because it causes errors during the compilation phase. compareTo()java.lang.String

3. Forgot to initialize objects that are elements of the array.

In Java, an array of objects is actually an array of object references. Creating an array is simply creating a set of references that don't point to anything (that is, they are null). To actually create a "full" array of objects, you need to initialize each element of the array. Many students don't understand this; they believe that by creating an array of objects, they automatically create the objects themselves. (In most cases, students bring this concept from C++, where creating an array of objects results in creating the objects themselves by calling their default constructor.) In the example below, the student wants to create 3 objects of the class StringBuffer. The code will compile without errors, but an exception will occur in the last line NullPointerException, where a non-existent object is accessed. Wrong example:
// Создаем массив из StringBuffer
StringBuffer [] myTempBuffers;
myTempBuffers = new StringBuffer[3];
myTempBuffers[0].add(data);
To avoid this error, you must remember to initialize the array elements. Corrected example:
// Создаем массив из StringBuffer и инициализируем элементы
StringBuffer [] myTempBuffers;
myTempBuffers = new StringBuffer[3];
for (int ix = 0; ix < myTempBuffers.length; ix++)
     myTempBuffers[ix] = new StringBuffer();

myTempBuffers[0].add(data);

4. Placing several classes with a modifier in one file at oncepublic

Java source files are associated in certain ways with the classes contained in those files. The relationship can be characterized as follows: Any Java class is stored in no more than one file. In any source code file you can place no more than 1 class with the modifier public. If there is a class with a modifier in the source code file public, the file name and the class name must be strictly the same (translation note: up to case, see point 1) Sometimes students forget about the 2nd rule, which leads to errors at the stage compilation. The error message for the 2nd and 3rd rules will be the same (which is what actually makes it difficult to recognize this error).

5. Substitution of a class field with a local variable.

Java allows you to declare variables inside a method whose name matches the fields of the class. In this case, local variables will take precedence and will be used instead of fields. The compiler will throw an error if variables with the same names are of different types. If they are the same types, there will be no compilation error, and the reasons for the program’s incorrect operation will be unclear. Wrong example:
public class Point3 {
    int i = 0;
    int j = 0;
    int k = 0;

    public boolean hits(Point[] p2list) {
      for(int i = 0; i < p2list.length; i++) {
        Point p2 = p2list[i];
        if (p2.x == i && p2.y == j)
          return true;
      }
      return false;
    }
}
There are several ways to fix this error. The simplest is to access class fields using the implicit this: pointer this.Name_поля. The best way is to rename the class field or local variable, then the substitution will not occur. (approx. Transl.: The 2nd method is not our method. Moreover, it does not guarantee that I will not accidentally replace a field of a variable someday. An even greater difficulty arises with inheritance, when I do not see at all what fields the class has ) Corrected example:
// One way to fix the problem
  int i = 0;
  int j = 0;
  int k = 0;

  public boolean hits(Point[] p2list) {
    for(int i = 0; i < p2list.length; i++) {
      Point p2 = p2list[i];
      if (p2.x == this.i && p2.y == this.j)
        return true;
    }
    return false;
  }

  // *****************************
  // Лучший способ
  int x = 0;
  int y = 0;
  int z = 0;

  public boolean hits(Point[] p2list) {
    for(int i = 0; i < p2list.length; i++) {
      Point p2 = p2list[i];
      if (p2.x == x && p2.y == y)
        return true;
    }
    return false;
  }
Another possible place for this error to occur is by setting the method parameter name to be the same as the class field name. This looks good in constructors, but is not suitable for normal methods.

approx. translation

a little chaotic, but that's the gist

public class Test {
   private int param = 0;

   public Test(int param) {
      this.param = param;
   }
}

that is, everything looks beautiful in the constructor, but this should not be used for ordinary methods.

6. Forgot to call the parent (superclass) constructor

When a class extends another class, each subclass constructor must call some superclass constructor. This is usually achieved by calling the superclass constructor with the method super(x)placed on the first line of the constructor. If there is no call in the first line of the constructor super(x), the compiler itself inserts this call, but without parameters: super(). (approx. trans.: x...se, but I didn’t know) Sometimes students forget about this requirement. Usually this is not a problem: the call to the superclass constructor is inserted by the compiler and everything works fine. However, if the superclass does not have a default constructor, the compiler will throw an error. In the example below, all superclass constructors java.io.Filehave 1 or 2 parameters: Erroneous example:
public class JavaClassFile extends File {
    String classname;
    public JavaClassFile(String cl) {
        classname = cl;
    }
}
The solution to the problem is to insert an explicit call to the correct superclass constructor: Corrected example:
public class JavaClassFile extends File {
    String classname;
    public JavaClassFile(String cl) {
        super(cl + ".class");
        classname = cl;
    }
}
A more unpleasant situation occurs when the superclass has a default constructor, but it does not fully initialize the object. In this case, the code will compile, but the output of the program may be incorrect or an exception may occur.

7. Incorrectly catching exceptions

Java's exception handling system is quite powerful, but difficult for beginners to understand. Students who are proficient in C++ or Ada usually don't have the same difficulties as C and Fortran programmers. The examples below show some common mistakes. In this example, the exception is not named. The compiler will indicate this error at the compilation stage, so it is easy to fix it yourself. Wrong example:
try {
    stream1 = new FileInputStream("data.txt");
} catch (IOException) {
    message("Could not open data.txt");
}
Corrected example:
try {
   stream1 = new FileInputStream("data.txt");
} catch (IOException ie) {
   message("Could not open data.txt: " + ie);
}
The order of the blocks catchdetermines the order in which exceptions are caught. It must be taken into account that each such block will catch all exceptions of the specified class or any of its subclasses. If you do not take this into account, you may end up with an unreachable catch block, which the compiler will point out. In the example below SocketExceptionis a subclass of IOException. Wrong example:
try {
    serviceSocket.setSoTimeout(1000);
    newsock = serviceSocket.accept();
} catch (IOException ie) {
    message("Error accepting connection.");
} catch (SocketException se) {
    message("Error setting time-out.");
}
Corrected example:
try {
    serviceSocket.setSoTimeout(1000);
    newsock = serviceSocket.accept();
} catch (SocketException se) {
    message("Error setting time-out.");
} catch (IOException ie) {
    message("Error accepting connection.");
}
If it is possible for an exception to occur in your code that is not caught by any block try-catch, then this exception should be declared in the method header. RuntimeException( This is not necessary for exceptions - subclasses of a class ). Students sometimes forget that calling a method can throw an exception. The easiest way to fix this is to put the method call in a block try-catch. Wrong example:
public void waitFor(int sec) {
    Thread.sleep(sec * 1000);
}
Corrected example:
public void waitFor(int sec) throws InterruptedException {
    Thread.sleep(sec * 1000);
}

8. The access method has a typevoid

This is a very simple mistake. The student creates a method to access a variable, but specifies that the method does not return anything (places a modifier voidin the method header). To fix this error, you must specify the correct return type. Wrong example:
public class Line {
    private Point start, end;
    public void getStart() {
      return start;
    }
}
Corrected example:
public class Line {
    private Point start, end;
    public Point getStart() {
      return start;
    }
}
Specifying the wrong return type generates a whole class of errors. Typically the compiler will recognize these errors and report them so that students can correct them themselves. Author: A. Grasoff™ Read the continuation Link to the source: Mistakes of beginner java programmers
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION