Top 10 + 1 Common Mistakes Every Java Learner Makes

It is said, “Your friend will swallow your mistakes, your enemy will present them on a plate”. I am definitely not your enemy, but I want to present you some mistakes, specific to each Java beginner student and I will do it right here on this blogging “plate”. Sure there are only some of them, I collected from CodeGym.cc courses analytical System. If you don’t know yet, CodeGym is a practical Java course from scratch to upper intermediate.

So, here they are.

0. Assignment or comparison (= or ==)?

This is one of the first mistakes of students who learn Java from scratch. It is easy to confuse that = is an assignment operator whereas == is a relational operator. That’s a natural mistake because in math “=” is closer to Java’s “==”, than to Java’s “=”. Usually compiler catches such mistakes, however, they could be hidden from it. For example:

boolean myBoolean;
If (myBoolean = true) {
doSomething;
}

See? This block will be true anyway because you assign it to be true…

1. Comparing Strings with == operator.

A while after you did your first Java tasks (usually there are some console output and arithmetical problems) you learn String class. However, beginners often forget that particular string isn’t a representative of a primitive type like char or int, it’s an object. You can’t compare objects using == operator. Remember using the string.equals(Object object) function to compare strings (or other objects), not the == operator. Equals check the contents of the string, while the == operator checks whether the references to the objects are equal.

To be honest with you, string constants are usually “interned”. That means two constants with the same value can actually be compared with ==, but don’t really rely on that.Use .equals.

2. Different names of Class and the file where its code is.

This mistake was very popular (maybe even leader of all) some years ago. Now even beginners use modern IDE’s and it is on the verge of extinction. Anyway, it is useful to bear in mind that in Java file name and class name should be the same. If you name your file, for example, Test.java and write there some class CodeGymTest code:

//File name: Test.java
    public class CodeGymTest {
       public static void main(String[] args) {
          System.out.println("Hello world");
       }
}

You’ll get the next output:

Test.java:9: error: class CodeGymTest is public, should be
                    declared in a file named CodeGymTest.java
public class CodeGymTest
^
1 error

By the way, if you remove public modifier from the class name, your program will run.

3. Accessing non-static members from the main method or other static methods

Pretty often beginners don’t know how to work with static context. Static variable is the one shared among all instances of a class. Therefore, there’s only one copy of it which is shared by all objects. So we can’t work with non-static variable in a “static way”. This mistake usually happens in the main() method (which is static!), when novice programmer attempts to access an instance variable or method. If you try such code

public class MyExample {
   public String myString;
public static void main(String[] args) { 
        myString = “non static String”;
}
   }

We’ve got compile error:

non-static variable number cannot be referenced from a static context.

What should we do to avoid this? First of all, we can make our variable static, but it is not always meets the program purpose. One of the solutions is to create an object of our class:

public class MyExample {
    public String myString;
public static void main(String[] args) {
MyExample myExample = new myExample();
        myString = “non static String”;
}
  }

Remember, you can work with static variables or methods from static or non-static context. You can work with non-static elements using object reference.

4. Array index is out of Array bounds

It is an extremely popular mistake among beginner programming students. The reason of such popularity is, that the very first more or less complicated tasks are about arrays and cycles. Very easy example:

String[] name = { "Snoopy", "Woodstock", "Charlie Brown" };
for (int i = 0; i <= name.length; i++) {
   System.out.println(name[i]);
}

The cycle starts from zero element “Snoopy”, then goes to the first “Woodstock” and to the second one “Charlie Brown”… and tries to print the third element, but we don’t have it (our “third” is a “second” such as “first” is number zero). Here the mistake is pretty obvious, but it is not always like this.

Cycles and arrays are pretty tough for rookies. However, practice makes diamonds. There are hundreds Arrays & Cycles tasks on CodeGym. Try to solve them (it is free for now on!) to get confident skills.

5. Puting “;” wrong in cycles or conditionals

In the block below you don’t print any of array’s members. First, the cycle is ending with “;” so nothing happens. Even more: the program won’t work because your int i works only inside the cycle and it ends with “;”.

public static void main(String[] args)  {
            int [] myArray = {2,5,7};
            for (int i=0; i<3; i++);
            {
                 System.out.println(myArray[i]);
            }
       }

If you try something like this:

public static void main(String[] args)  {
            int [] myArray = {2,5,7};
            int i = 0;
            for (i=0; i<3; i++);
            {
               System.out.println(myArray[i]);
            }
         }

You’ve got java.lang.ArrayIndexOutOfBoundsException, because System.out.println tries to print element #3 and only this one, but we don’t have such an array member. The last one is the second and it is 7.

The same story with ; and conditions. For example:

public static void main(String[] args)  {
            int [] myArray = {2,5,7};
           if (myArray[0] > myArray[1]);
            System.out.println("it is");
        }
   }

The condition is not satisfied here, but “it is” would be printed because of “;” after if construction.

If you start your CodeGym learning, you’ll get your first coding tasks with cycles on the level 4 Java Syntax quest. I guess you’ll forget about this kind of mistakes solving enough problems.

6. Missing the ‘break’ Keyword in a Switch-Case construction

The embarrassing thing about missing a “break” keyword is that there aren’t compiler error. However your code works the wrong way.

Look at the code example below, where we forgot to put a break in “case 0”. The program will work but it prints both “0” and “1” because switch construction ends its work with a break.

public static void switchCasePrimer() {
        int counting = 0;
        switch (counting) {
            case 0:
                System.out.println("0");
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
                break;
            default:
                System.out.println("Default");
       }
}

This rule has an exception. Switch block can finish its work with return operator

public class test {
    public static void main(String[] args) {
        System.out.println(showSwitch(1));
    }
    public static int showSwitch(int condition) {
        switch (condition) {
            case 1:
                System.out.println(1);
                return 1;
            case 2:
                System.out.println(2);
                return 4;
            case 3:
                System.out.println(3);
                return 8;
            default:
                System.out.println("default");
                return 256;
        }
    }
}

In this case, switch finishes its job right after case 1.

7. Mess with pass by value and pass by reference

If you pass a primitive data type, such as a char, int or double, to a method, you are passing by value. That means a copy of the data type would be duplicated and passed to your method. If that data is modified inside the method, there is no influence on the “original” data outside the method.

public class Main {
    public static void swap(int i, int j)
    {
        int temp = i;
        i = j;
        j = temp;
        System.out.println("from swap method i = " + i + ", j = " + j);
    }
    public static void main(String[] args) {
        int i1 = 1;
        int j1 = 2;
        swap(i1,j1);
        System.out.println("from main method i = " + i1 + ", j = " + j1);
    }
}

When you pass a Java object, for example, array or string to a method, that means you are passing a reference (address of your data), not a duplicate. So if you change the data in a method, it will be changed outside it as well.

public class Main {
    static int[] outer = new int[3];
    public static void swap(int[] array) {
        System.out.println("(swap) Before swap :" + Arrays.toString(array));
        int first = array[0];
        int last = array[array.length - 1];
        array[0] = last; 
        array[array.length - 1] = first;
        System.out.println("(swap) After swap :" + Arrays.toString(array));
     }
    public static void main(String[] args) {
        outer[0] = 0;
        outer[1] = 1;
        outer[2] = 2;
        swap(outer);
        System.out.println("(main) After swap :" + Arrays.toString(outer));
    }

8. Attempt to work with uninitialized field or variable

Work with an object type without initialization is pretty dangerous.

Class variables are initialized by the default value (0 for int, 0.0 for double, false for boolean, null for non-primitive types (objects).

public class Test2 {
    static String test;
    public static void main(String[] args) {
      System.out.println(test);
    }
}

The output is:

Null

When you work with a local method variables you need to initialize them manually, otherwise, you’ll get a compilation error.

public class Test2 {
    public static void main(String[] args) {
        String test2;
     System.out.println(test2);
    }
}

The output is:

Error:(6, 28) java: variable test2 might not have been initialized

9. Forgetting about integer division

If you divide one int to another int, you’ll get int again. So ½ = 0, not 0.5 in this case:

public static void main(String[] args) {
        int i = 1;
        int j = 2;
  int k = i/j; //here we’ve got 0
  }

You may learn about division and real types from Java Syntax quest of CodeGym and solve a lot of coding tasks related to the topic.

10. Mess with an order of calling constructors in Child objects

When you try to create an instance of a Child class, Child is called first, and Parent after it. Order of constructors execution in Parent-Child relationship builds from basic (Parent) class to inherited (Child).

public class Test3 {
    static class Parent {
        Parent() {
            System.out.println("a Parent is created");
        }
    }
    static class Child extends Parent {
        Child(){
            System.out.println("a Child is created");
        }
    }
    public static void main(String[] args) {
        Child child = new Child();
    }
}

Output:

a Parent is created
a Child is created

If you join CodeGym, you’ll meet OOP and inheritance in Java Core Quest. There are really many tasks in this topic. So sooner or later you’ll get a subtle understanding of OOP principles.

Conclusions

I presume, there is no article that can accumulate all the potential mistakes of newbie Java students. Nevertheless, such lists are very useful to avoid the popular mistakes… and have time to find less trivial issues! Praemonitus, praemunitus (* forewarned is forearmed).

However, the most important step is not avoiding mistakes but practice coding itself. That’s why we created CodeGym, Java Core course with more than 1000 practicing tasks, fun lectures and instant feedback on your improvements. When you make a mistake, popular or rare, CodeGym System warning you about it and gives you recommendations to avoid it. Try the course by yourself, it is free for now on.

Don’t stop practice and you become a better software developer for sure. Good luck with your learning!`

No Comments Yet