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

8 common mistakes of novice programmers

Published in the Random EN group
Hello! Today we will look at a list of 8 common mistakes made by beginning (and not only) Java developers. You will find many such collections on the Internet: many of them are similar to each other. When we compiled this list, we were guided by one criterion: whether we ourselves made these mistakes during study and work :) They are not prioritized and are equally important for understanding and remembering.
  1. Comparing objects using ==.

    The operator ==compares object references.

    The references point to addresses in memory, and if they are at different addresses, the 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 speaking, 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, to correctly compare objects, you need to redefine this method in accordance with the criteria that are important in a specific program for specific objects. You determine the criteria for equality yourself.

    The only thing you shouldn't forget 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 have 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 a class object, and all field variables belong to specific objects. This is the contradiction that leads to error.

    On the contrary, by the way, it is possible: 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 of how parameters are passed to methods: by reference or by value.

    Objects and primitives are passed to methods as parameters in different ways: the former by reference, the latter by value.

    Beginners often find this concept difficult to grasp, resulting in their code behaving 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 don’t 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 applies not only to compliance with certain “technical” principles, but also to 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 yours alone. You can transfer to another project in the company, and it will be inherited by your colleagues, who will clearly not be happy when they get something like this:

    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 brilliant in terms of performance, but if it is impossible to read and understand how it actually works, its value, alas, is small.

    Adhere to writing standards, and your code, even if it’s 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 of class workString

    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 clearly 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 correctly compare strings in your code. In one of our lectures we discussed this topic in detail.

  6. Incorrect handling of exceptions.

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

    Firstly, there is no universal recipe. Errors in a program are different, and the scripts for processing them, respectively, are different. 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 many more options for doing things wrong here than anywhere else.

    Common antipatterns are listed here:

  7. Неполное понимание работы операторов (арифметических, логических и других).

    8 common mistakes of novice programmers - 2

    Простой пример. Сможешь сходу сказать, что выведет этот code?

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

    Если ты ответил неправильно or наугад, значит, в этой области пока есть пробелы:)

    Код выведет false, потому что приоритет у оператора сравнения == выше, чем у постфиксного инкремента ++. Поэтому сначала будет выполнено сравнение 7 == i, и только потом - операция i++.

    По этой теме, кстати, у нас тоже была подробная лекция. Вот link, если пропустил.

  8. Пропуск слова break в операторе switch.

    Эту ошибку, вероятно, допускали многие из читателей!)

    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");
               }
           }
       }
    }

    В результате на них обрушивается водопад из всех возможных вариантов:

    Вывод:

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

    Оператор break прерывает работу оператора switch в момент, когда отработал один из вариантов. Не стоит о нем забывать, иначе результат может быть неожиданным :)

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