JavaRush /Java Blog /Random EN /8 common mistakes novice programmers make

8 common mistakes novice programmers make

Published in the Random EN group
Hello! Today we will look at a list of 8 common mistakes of novice (and not only) Java developers. On the Web you will find many such collections: many of them are similar to each other. When we compiled this list, we focused on one criterion: did you make these mistakes yourself during your studies and work :) They are not ranked by priority and are equally important for understanding and remembering.
  1. Comparing objects with ==.

    The operator ==compares object references.

    The links point to addresses in memory, and if they are at different addresses, comparison through ==will return false.

    public class Car {
    
       String model;
       int maxSpeed;
       int yearOfManufacture;
    
       public Car(String model, int maxSpeed, int yearOfManufacture) {
           this.model = model;
           this.maxSpeed = maxSpeed;
           this.yearOfManufacture = yearOfManufacture;
       }
    
       public static void main(String[] args) {
           Car ferrari = new Car("Ferrari 360 Spider", 280, 1996);
           Car ferrariTwin = new Car("Ferrari 360 Spider", 280, 1996);
           System.out.println(ferrari == ferrariTwin);
       }
    }

    To compare objects in a class, Objectthere is a special method - equals(). Its default implementation, frankly, is so-so:

    public boolean equals(Object obj) {
       return (this == obj);
    }

    In the class itself, Objectthe logic of the method equals()is implemented as a comparison of two references. In turn, for the correct comparison of objects, you need to override this method in accordance with the criteria that are important in a particular program for specific objects. The criteria for equality are determined by you.

    The only thing to keep in mind is the list of requirements for a proper override equals(). You can easily find them on the Internet, but our cool students have already made an article on this topic .

  2. Using non-static variables in static methods (and vice versa).

    If you've ever seen the inscription " Non-static variable x cannot be referenced from a static context " - welcome to the club :)

    Static methods do not have access to non-static class variables.

    This is logical: after all, a static method can be called without creating an object of the class, and all field variables belong to specific objects. This is the contradiction leading to the error.

    On the contrary, by the way, you can: it is permissible to use static variables in non-static methods:

    public class Main {
    
       public int x = 10;
    
       public static int staticX = 100;
    
       public static void main(String[] args) {
    
           System.out.println(x);//ошибка компиляции, так нельзя!
       }
    
       public void printX() {
    
           System.out.println(staticX);//а так можно!
       }
    }
  3. Misunderstanding how parameters are passed to methods: by reference or by value.

    Objects and primitives are passed to methods as parameters in different ways: the first - by reference, the second - by value.

    This concept is often difficult for beginners to understand, and as a result their code behaves unexpectedly:

    public class Main {
    
       public static void main(String[] args) {
    
           int x = 7;
           incrementNumber(x);
           System.out.println(x);
    
           Cat cat = new Cat(7);
           catLevelUp(cat);
           System.out.println(cat.getAge());
    
       }
    
       public static void catLevelUp(Cat cat) {
    
           cat.setAge(cat.getAge()+1);
       }
    
       public static void incrementNumber(int x) {
           x++;
       }
    }

    If in this example you do not know exactly which number will increase and which will not (the usual number or the age of the cat), then re-read our lecture on this topic again .

  4. Ignoring the rules of writing code.

    And this concerns not only the observance of certain "technical" principles, but also banal naming conventions.

    All these rules “ how to name variables ”, “ how to write method names ” were invented for a reason. This really greatly affects the readability of the code.

    After all, the code will not always be only yours. You can transfer to another project in the company, and it will be inherited by your colleagues, who will obviously not be delighted when they get something like this to work:

    public class Cat {
    
       private int S_O_M_E_T_H_I_N_G = 7;
       public String striiiiiiiiiiiiiing;
       protected double X3_4TO_ET0_TAK0E = 3.14;
       boolean random = Math.random() > 0.5;
    
    }

    Your code may be ingenious in terms of performance, but if it is impossible to read and understand how it actually works, its price, alas, is small.

    Adhere to the standards of writing, and your code, even far from ideal, will at least be read by more experienced comrades and tell you what can be improved in it from a technical point of view :)

  5. Misunderstanding how the class worksString

    public class Main {
    
       public static void main(String[] args) {
    
           String s1 = "Я изучаю Java";
           String s2 = new String("Я изучаю Java");
    
           System.out.println(s1 == s2);
       }
    }

    If you don't know why this code outputs false, you obviously need to improve your knowledge :)

    Beginners often do not know what it is String Pooland how it works.

    As a result, it is not entirely clear how to properly compare strings in your code. In one of our lectures, we discussed this topic in detail.

  6. Incorrect work with exceptions.

    This is true not only for beginners, but also for experienced developers. There are several reasons.

    First, there is no universal recipe. Errors in the program are different, scripts for their processing, respectively, too. Secondly, not everyone understands the structure stackTrace, and there are a lot of error handling antipatterns, and each of them is “wrong” in its own way. So there are a lot more options to do wrong here than anywhere else.

    Common anti-patterns are listed here:

  7. Incomplete understanding of the operation of operators (arithmetic, logical, and others).

    8 common mistakes novice programmers make - 2

    A simple example. Can you tell right off the bat what this code will output?

    public class Main {
    
       public static void main(String[] args) {
    
           int i = 6;
           System.out.println(7 == i++);
       }
    }

    If you answered incorrectly or at random, then there are still gaps in this area :)

    The code will output falsebecause the comparison operator has ==higher precedence than the postfix increment ++. Therefore, the comparison will be performed first 7 == i, and only then the operation i++.

    By the way, we also had a detailed lecture on this topic. Here is the link if you missed it.

  8. Skip a word breakin a statement switch.

    This mistake was probably made by many of the readers!)

    public class Main {
    
       public static void main(String[] args) {
    
           int i = 1;
    
           switch (i) {
    
               case 1: {
                   System.out.println("Число равно 1");
               }
               case 2: {
                   System.out.println("Число равно 2");
               }
               case 3: {
                   System.out.println("Число равно 3");
               }
           }
       }
    }

    As a result, a waterfall of all possible options falls on them:

    Conclusion:

    
    Число равно 1
    Число равно 2
    Число равно 3

    The operator breakinterrupts the work of the operator switchat the moment when one of the options has been completed. Do not forget about it, otherwise the result may be unexpected :)

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION