Common Java Errors And How To Avoid Them

January 26, 2022
common java errors and how to avoid them



Introduction

Whether you are a new Java developer or an experienced one, errors are inevitable in your code. When writing Java code, you will encounter various errors, but most of them are easily avoidable with some minor tips to consider.

In this article, we will be discussing the following ten most common Java errors and how you can spot and fix them in your code.

1. Mistyping the name of a method when overriding

Overriding is a very handy feature in Java and other OOP languages. One of the very common Java errors is mistyping the name of the method name when overriding it. This error can be very frustrating to detect as compilers will not identify it. When the method’s name is mistyped, you are no longer overriding a method, and you have created another method with the same parameter and return type.

Don’t forget to double-check the method name when overriding it to avoid this error. Still, if the error occurs, you can use a trace debugging tool to step through your code line by line to check if your overloaded method is called or not.

2. Using “=” instead of “==” for comparing values

This is among the most common Java errors. Developers working with other programming languages often make this error as “==” is not used in many other languages. Another reason behind this error can be a simple typing error.

Fortunately, the compiler can detect it whenever you use “=” instead of “==” as the = sign is used for assignment in Java. It will result in the following error, “Can’t convert <data type1> to boolean”, where <data type1> is a Java type that you are attempting to assign instead of comparing them.

3. Using “==” instead of the .equals method for comparing objects

When the “==” operator is used to compare two objects, it compares the object references to check if they point to the same object. It will not compare their values. You must use the .equals method to compare the values of two objects to ensure that they are equal.

In this example, I am demonstrating the use of the .equal method to compare two strings (String is an object!). It would be inaccurate if I used “==” to compare them.

String str1 = "aaa";
String str2 = "bbb";

if ( (str1 + str2).equals("aaabbb") )
{
   //Method statements
}

4. Confusion over passing by value and passing by reference

This is also among the common Java errors often made by new Java developers. As Java uses both passing mechanisms, you need to understand when you should be passing the parameters by value and when you should be passing them by reference.

When a primitive data type like int is passed to a function, it is passed by value. In this way, a copy of that value is passed to the function. Any modification made inside the function does not affect the original value by passing a copy.

On the contrary, when a Java object like an array or a string (Yes! String is not a primitive data type) is passed to a function, it is passed by reference. It means that you are passing a reference to the original object, not a copy of it. Any changes to the object’s member variables will affect the original object.

Now, interchanging these passing methods can result in a logical error as it will not be as per your intention, and it will also not be identified by the compiler. The best solution would be to properly understand the uses of both of them before applying them.

5. Writing blank exception handlers

This is one of the common Java errors made by amateur developers. When you leave the exception handlers blank, it will still get the job done of preventing the crash, and you can skip the error messages. The problem will occur when you have to find out the cause of an exception. As you would not have written any error messages, it will be next to impossible to find out which exception has occurred.

The best solution is to use the try-catch exception around your code to catch if any exception is thrown, and it will print out a simple message. You will not have to write a custom handler for every exception.

See this simple example below:

public static void main(String args[])
{
    try {
          //code statements
    }
    catch (Exception e)
    {
          System.out.println ("Error Message "+e );
    }
}

6. Forgetting that array starts with the 0th index in Java

Arrays and other objects are zero-indexed in Java. It means that the index of the first element is always 0.

Take a look at this small code below:

//Creating a small array of 3 integers
String[] myArr = new int[3];

//Index of first element is 0 so,
myArr[0] = 1;

//Second index is actually 1
myArr[1] = 2;

//Final element's index will be 2
myArr[2] = 3;

If you ever try to access myArr [3], you would be attempting to access the fourth element, not the third. This will result in an ArrayOutOfBoundsException. The same error can be faced while dealing with strings if you go beyond the (length of string -1) as they are also zero-indexed. Various other parts of Java are also zero-indexed, such as the Java.util.Calendar class in which months also starts with 0.

Surprisingly, the days in the calendar class start with 1. Remembering all these different rules might seem confusing, but you can go through the documentation when using a new class to be sure.

7. Capitalization error in naming

This is one of the most common Java errors every Java developer makes. You have to remember some very simple rules about naming conventions of built-in functions in Java. They need to be capitalized in a certain way. The errors caused by these mistakes can also be very puzzling as it simply states that the method does not exist instead of recognizing that a capitalization is missing in the name.

With time, you can make a habit of writing all the variables and functions correctly, and you need to remember the following rules:

  • all the methods and member variables in Java begin with lowercase letters.
  • All methods and member variables use capitalization where a new word starts in their name except the first word like getDoubleValue().

If you follow these two rules, you can gradually reduce the capitalization errors in your code.

8. Forgetting the return statement

You can encounter a “missing return statement” error when you forget to add the return statement at the end of the function. This is again among common Java errors made by beginners and experienced developers. A non-void method that returns a value must have a return statement. This error can also occur if you have mentioned a return statement but did not return the value declared in the method definition.

9. Null pointers

Null pointer error is also among the most common Java errors developers make. When you try to access an object and the reference to that object is null, as a result, the NullPointerException is thrown. Unfortunately, compilers cannot detect this error, and it can only be detected at runtime. The reason behind the null pointer can vary, but, in most cases, it is because either the object is not initialized, or the function called to access the object is returning a null value.

The first solution is to initialize the objects to avoid the null value. Some built-in functions return the null to indicate an error. If a built-in function you are using in your code indicates null could be returned, be sure to check the returned value once before using the object reference.

10. Incompatible data types

It is also among very common Java errors faced when a different value is assigned to another type of variable. A common example would be assigning a string into an integer type variable or vice versa. An easy fix would be to either make adjustments in your code or use the functions to convert the type of data to be assigned (casting).

See Also: Understand The “Out Of Memory Error” Exception In Java

Conclusion

These are some of the most common Java errors we all have made. You can avoid repeating these common Java errors once you learn to identify and correct them.



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US