Java Language Top 10 Java Errors with Solutions

Top 10 Java Errors with Solutions

Syntax Errors

The most obvious errors one can face as a beginner are syntax errors. It’s completely fine to face such errors as you’re just starting to learn the language. You can look at syntax errors as the linguistic rules in any language. Once you start following the rules it gradually fits your coding style. For additional relevant information, you may refer to java syntax articles.

The first problem we’re gonna talk about is the Java naming conventions. A lot of beginners don’t bother learning or taking care of them but these standards reflect the maturity of a programmer and make the code easier to read. Hence, we highly recommend you follow these if you seriously want to learn Java.

Java Naming Conventions

You won’t receive a compile-time or run time error for not following the naming conventions. However, these are necessary to write decent code.

In Java, in order to use a resource, you have to name it. The names of variables, methods and classes are called “identifiers”. Identifiers need to follow certain rules written as under.

  • Identifies can only start with either a letter (a,b,..,z / A,B,...,Z), dollar sign ($) or an underscore.
  • The names of variables and methods are written in lowerCamelCasing.
  • The names of classes are written in UpperCamelCasing.
  • You can not use a keyword like an int, double, float, String etc as an identifier.

Missing Semicolon

Initially missing semicolons at the end of each line in Java can be very normal. However, it goes with practice. You can consider the semicolon (;) in Java similar to a period / full stop (.) in the English language.

Example

class Main {
public static void main(String args[]) {
    String day = "Monday"
    System.out.println("Today is " + day + ".");
  }
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Syntax error, insert ";" to complete BlockStatements
	at topJavaErrors.JavaErrors.main(JavaErrors.java:3)

You can read the error thrown and place the semicolon at the line detected by the IDE to fix this.

Missing Parenthesis / Braces

The missing parenthesis or im-balancing the closing brace can be categorized as the second most recurring issue for beginners. Imbalanced braces can be easier to detect in a well-indented code. Make sure you indent your code well. If you’re not comfortable with it yet, then here’s an Eclipse shortcut Ctrl + Shift + F for beginners.

Example

class Main {
public static void main(String args[]) {
    String day = "Monday"
    System.out.println("Today is " + day + ".");
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Syntax error, insert "}" to complete ClassBody
	at topJavaErrors.SyntaxErrors.main(SyntaxErrors.java:5)

Add the closing brace at line 6 for a perfectly running program.

Java does not allow to assign a variable a value that’s different from its data type, unlike other languages like Python or JavaScript. For example, you can not store the value of a variable having data type int to a String type variable.

Example

public class IllegalTypeAssignment {
	public static void main(String[] args) {
		String name = "Alexa";
		int age = 10;
		
		name = age;
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from int to String
	at topJavaErrors.IllegalTypeAssignment.main(IllegalTypeAssignment.java:6)

Either cast the int to a String or use another variable of the same type.

Missing Return Statement

It can be quite easy to forget returning the value from a method whose return type is not “void”. In this case, the compiler shows the error as elaborated in the example.

Example

public class ReturnType {
	public static int getSum(int num1, int num2) {		

		int sum = num1 + num2;
	}
	public static void main(String[] args) {

		System.out.println("Sum of numbers = " + getSum(5,7));
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	This method must return a result of type int
	at topJavaErrors.ReturnType.getSum(ReturnType.java:5)	

You can add the return statement to eliminate this exception.

Return statement not allowed with the void method

On the contrary, you’ll receive a compile-time if you return an integer, a boolean or even null from a void method. The example shows how it can cause an error.

Example

public class ReturnType {
	public static void printSum(int num1, int num2) {		
		int sum = num1 + num2;
            System.out.println("Sum of numbers = " + sum);
		return sum;
	}	
	public static void main(String[] args) {
		printSum(5,7);
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The operator + is undefined for the argument type(s) String, void
      at topJavaErrors.ReturnType.main(ReturnType.java:5)

Remove the return statement to eliminate this exception.

Invalid return type

Talking of the return types, it's easier to return a double value from a method having int as its return type. Although, double and int are both numbers and look similar, however, either you have to cast the value to the desired type or alter the method’s return type with what you need.

Example

public class ReturnType {
	public static int getDouble(double num) {		
		double doubleValue = num * 2;
		return doubleValue;
	}
	public static void main(String[] args) {
		System.out.println("Double of number = " + getDouble(5));
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from double to int
	at topJavaErrors.ReturnType.getDouble(ReturnType.java:8)

Unreachable / Dead Code

The unreachable or dead code occurs when there’s a certain piece of code that can never be executed. Such snippets are the ones mostly written after the return statements or after the conditions that will never be true.

Example

public class ReturnType {
	public static double getDouble(double num1) {		
		double doubleValue = num1 * 2;
		return doubleValue;	
		double tripleValue = num1 * 3;
	}

	public static void main(String[] args) {
		System.out.println("Double of number = " + getDouble(5));
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Unreachable code
	at topJavaErrors.ReturnType.getDouble(ReturnType.java:5)

Null Pointer Exception

Null Pointer Exceptions can be easy to receive, but hard to bust sometimes if not paid close attention to. These runtime exceptions can crash your application while the users are using it. So make sure to test your program thoroughly to save anyone from having a bad user experience.

Example

public class NullPtrException {
	public static void main(String[] args) {

		String myCity = null;
		if (myCity.equals("Lahore")) {
		    System.out.println("true!");
		}
		else {
		    System.out.println("false");
		}
	}
}

Output

Exception in thread "main" java.lang.NullPointerException
	at topJavaErrors.NullPtrException.main(NullPtrException.java:5)

You can not compare null until it’s replaced by a valid value.

Misspelt Name while Method Overriding

(Before moving on to this section, we expect you to be familiar with method overriding.) Java demands the overridden methods to be named exactly the same. If you forgetfully make a typo, or there’s even a slight difference in the names of methods, the compiler fails to identify & map the method to be overridden.

Example

class Shape {
    public void message() {
        System.out.println("I am an abstract shape.");
    }
}

class Triangle extends Shape {
    @Override 
    public void messages() {
        System.out.println("I am a triangle.");
    }
}

public class MethodOverriding {
	public static void main(String[] args) {

		Shape parking = new Shape();
		parking.message();  // Prints "I am an abstract shape."

		Shape dates = new Triangle();  
		dates.message();   // Prints "I am an abstract shape." 
		// and not "I am a triangle" because of misspelt method 
		// "messages" in class Triangle.
	}
}

Output

I am an abstract shape.
I am an abstract shape.

Conclusion

By now you must have a sound familiarity with some common errors in Java. By looking at these is one way to beware of them and by practicing you’ll train your mind to get rid of them. So keep learning, keep growing and most significantly never stop practicing!