Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Types of Errors in Java
3.
Syntax Errors or Compilation Errors
3.1.
Examples of Syntax/Compilation Errors
3.2.
How to avoid Syntax Errors?
4.
Runtime Error
4.1.
What are Exceptions?
4.2.
Examples of Runtime Errors
4.3.
How to avoid Runtime Errors in Java
5.
Logical Error
5.1.
Examples of Logical Errors
5.2.
How to avoid Logical Errors
6.
Frequently Asked Questions
6.1.
What is the best way to debug errors in Java?
6.2.
What is a null pointer exception error in Java? 
6.3.
What is an array index out of bounds error in Java?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Types of Error in Java

Author Harshita Vyas
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java is one of the popular programming languages used for developing various applications, ranging from mobile apps to enterprise software. As with any programming language, errors can occur in Java code, leading to unexpected behaviour or program failures. In this article, we shall explore the various types of errors that can occur in Java, including syntax errors, runtime errors, and logical errors. We will also discuss how to identify and avoid these errors to ensure that your Java code runs smoothly and efficiently.

Types of Error in Java

Types of Errors in Java

 

Major Types of Errors in Java

There are several types of errors that occur in Java, including syntax errors, runtime errors, and logical errors. They are

  • Syntax Errors or Compilation Errors: These occur when the code violates the rules of the Java syntax. These errors are usually caught by the Java compiler during the compilation phase.
     
  • Runtime Errors: These errors occur when the code encounters an unexpected behaviour during its execution. These errors are usually caused by flawed logic or incorrect assumptions in the code and can be difficult to identify and fix.
     
  • Logical Errors: These occur when the program is executing correctly, but the result is not what was intended. These errors can be difficult to identify and fix, as the program is running correctly but producing unintended results.
     
  • Linking Errors: Linking errors occur when the Java Virtual Machine (JVM) tries to link a class file during runtime but encounters a problem. This can happen if a required class or library is missing, or if there is a problem with the syntax or format of the code. 
     
  • Class Loading Errors: Class loading errors occur when the JVM attempts to load a class into memory but encounters a problem. This can happen if the class file is missing or corrupted, or if there is a problem with the classpath.
     

Also read, Duck Number in Java and Hashcode Method in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax Errors or Compilation Errors

Syntax errors or compilation errors are some of the most common types of errors in Java that programmers encounter. These errors occur when the code violates the rules of the Java syntax, making it impossible for the Java compiler to translate the code into a machine-readable format. Here are some examples of Java code that can result in syntax errors or compilation errors:

Examples of Syntax/Compilation Errors

Example 1: Missing semicolon

Code:

public class Main 
{
   public static void main(String[] args)
   {
      System.out.println("Hello, World!")
   }
}

 

Output:

Missing semicolon

In this example, there is a missing semicolon after the print statement. This will result in a syntax error, and the Java compiler will not be able to compile the code.

Example 2: Assignment Errors

Code:

public class Main 
{
   public static void main(String[] args) 
   {
      int x = "5";
   }
}

 

Output:

Assignment Errors

In this example, the variable ‘x’ is declared as an integer, but its value is assigned as a string. This will result in a compilation error because the Java compiler cannot convert a string to an integer.

Example 3: Missing Brackets

Code:

public class Main
{
    public static void main(String[] args) 
    {
        int x = 5;
        if x == 5 {
            System.out.println("x is 5");
        }
    }
}

 

Output:

Missing Brackets

In this code example, the if statement is missing the opening and closing parentheses, causing a syntax error.

Example 4: Misspelt variable or keywords

Code:

public class Main 
{
   public static void main(String[] args) 
   {
      	String Greeting = “Hello World!”;
		System.out.println(greeting);
   }
}

 

Output:

Misspelt variable

In this example, we have misspelt the variable ‘Greeting’ as ‘greeting’, which lead to a syntax error.

Let us look at one more code where there is a misspelt keyword:

Code:

public class Main
{
   public static void main(String[] args) 
   {
   		String name = “Jack”;
	    System.out.println(name);
   }
}

 

Output:

Misspelt keyword

Here, we have misspelt the keyword ‘String’. S should be capitalized. Thus, the compiler shows a syntax error.

Example 5: Type Errors

These errors occur when the types of variables used in the program are incompatible. For example, trying to add an integer and a string can result in a type error.

Code:

public class Main
{
   public static void main(String[] args) 
   {
      String a = “Riya”;
	  int b = 15;
	  String c = a + b;
	  System.out.println(c);
   }
}

 

Output:

Type Errors

In this example, we are trying to add a string to an integer, thus this is resulting in error.

How to avoid Syntax Errors?

There are several ways to avoid syntax errors in Java, including

  • Use a good IDE: A good Integrated Development Environment (IDE) such as can help you catch syntax errors as you write your code.
     
  • Pay attention to syntax rules: Java has a specific set of syntax rules that you need to follow. Make sure you understand these rules and use them consistently.
     
  • Test your code frequently: Test your code frequently as you write it to catch any syntax errors early.
     
  • Use comments: Adding comments to your code can help you identify potential syntax errors before they happen.

 

By following above mentioned tips, you can reduce the likelihood of syntax errors in your Java code and write cleaner, more efficient code.

Also see,  Swap Function in Java

Runtime Error

Runtime errors in Java occur when a program is running and encounters an unexpected condition or action that cannot be handled by the program. They are one of the most time-consuming types of errors in Java that a programmer encounters. These can even hang the entire program. These errors cannot be detected during compilation because they are related to the runtime behaviour of the program. A runtime error in Java is also known as an exception.

What are Exceptions?

In Java, exceptions are used to handle runtime errors that occur in the middle of the execution of a program. An exception is an object that represents an error or an abnormal condition that has occurred in the program.

The try-catch block is used to handle runtime errors in Java. The try block contains the code that may cause an exception, and the catch block contains the code that handles the exception. Runtime errors are difficult to debug, as they may not occur immediately and may cause the entire program to hang.

Below is an example code snippet that demonstrates how to use exceptions in Java:

Code:

public class exceptionExample {
    public static void main(String[] args) {
        try {
            int num1 = 12;
            int num2 = 0;
            int result = num1 / num2; // This line of code will show an ArithmeticException
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Error occurred: " + e.getMessage());
        }
    }
}


Explanation:

In the above example, we are trying to divide an integer by zero, which is not a valid operation and will result in an ‘ArithmeticException’. To handle this exception, we have enclosed the potentially problematic code in a ‘try’ block and caught the exception in a ‘catch’ block. The catch block will execute if an exception occurs and will print an error message along with the exception message.

Other examples of exceptions in Java include ‘NullPointerException’‘ArrayIndexOutOfBoundsException’‘ClassCastException’, and ‘IllegalArgumentException’, among others. Each exception has its own specific use case and can be caught and handled using the same try-catch block syntax shown above.

Java contains two types of exceptions: checked and unchecked. Let’s discuss them one by one -

  1. Checked Exceptions: Checked exceptions are those which are checked at compile-time. These are exceptions that are expected to occur at runtime, but the compiler makes sure that the programmer has provided a way to handle them so that the program does not show runtime error. 
    Example: IOException - This is thrown when an I/O operation fails, such as when reading or writing to a file.
     
  2. Unchecked Exceptions: Unchecked exceptions are those that are not checked at compile-time. These are exceptions that occur due to programming errors or unexpected runtime conditions.
    Example: NullPointerException - This is thrown when a program attempts to access an object that is null.

Examples of Runtime Errors

Below are some examples of common runtime errors in Java:

Example 1: NullPointerException: This error occurs when a program attempts to use a null object reference. For example:

Code:

public class Main {
    public static void main(String[] args) {
        String str = null;
        int length = str.length(); // This will throw a NullPointerException because str is null
    }
}

 

Output:

NullPointerException

Here we assigned str to NULL. Then we access the length of str. Since, str is NULL, it will throw an exception.

To avoid this error, it is important to ensure that all variables are initialized before they are used. You should also check for null values before using them in your code.

Example 2: ArithmeticException: This error occurs when a program attempts to perform an illegal arithmetic operation, such as dividing by zero. For example:

Code:

public class Main 
{
    public static void main(String[] args) 
    {
        int num = 5 / 0; // This will throw an ArithmeticException because dividing by zero is not allowed
	}
}

 

Output:

ArithmeticException

In this example, we are trying to divide 5 by 0. This operation is not valid, and hence we get a runtime error (an ArithmeticException). This error can be avoided by checking for zero before performing a mathematical operation.

Example 3: ArrayIndexOutOfBoundsException: This error occurs when a program attempts to access an array element that is outside of the array bounds. For example:

Code:

public class Main 
{
    public static void main(String[] args) 
    {
        int[] arr = new int[3];
        int num = arr[3]; // This will throw ArrayIndexOutOfBoundsException 
	}
}

 

Output:

ArrayIndexOutOfBoundsException

In this example, we have declared an array arr having size 3. This means we can only access indexes 0, 1 and 2. But the program is trying to access index 3, which is out of bounds. This type of error also occurs when we try to access negative indexes. 

To avoid this error, you should always make sure that the index is within the bounds of the array. You can do this by using the length property of the array to get the number of elements in it.

Example 4: ClassCastException: This error occurs when a program attempts to cast an object to a type that is not compatible with its actual type. For example:

Code:

public class Main 
{
    public static void main(String[] args) 
    {
        Object obj = new String("Hello");
        Integer num = (Integer) obj; // This will throw a ClassCastException because obj is not an Integer object
	}
}

 

Output:

ClassCastException

In this example, we are trying to cast a string object to an integer object. This throws an error as a string object cannot be typecasted to an integer object.  

Example 5: OutOfMemoryError: This error occurs when a program runs out of memory. For example:

Code:

public class Main 
{
    public static void main(String[] args) 
    {
        List < Integer > list = new ArrayList < > ();
        while (true) {
            list.add(1); // This will eventually throw an OutOfMemoryError because the list will run out of memory
        }
    }
}

 

In this example the program will keep on running infinitely as the while loop is always true and thus the program will crash.

Must Read Type Conversion in Java

How to avoid Runtime Errors in Java

For avoiding runtime errors in Java, here are some best practices that developers can follow:

  • Always initialize variables: Always remember that uninitialized variables can lead to runtime errors. Therefore, one should always make sure to initialize the variables with the appropriate data type before using them in the program. For example, if you don’t initialize a string then it takes value NULL and it you try to find it’s size using .size() function, it will throw runtime error.
     
  • Check for null values: One should always check for null values before accessing any object or variable. This can lead to runtime error id we try to access the address of a null variable. Same example can be given as in the previous one.
     
  • Use exception handling: One must use try-catch blocks to handle exceptions in the program. This helps to prevent the program from crashing if an error occurs. This enables the program to run smoothly even if it encounters any runtime error.
     
  • Avoid infinite loops: Infinite loops can cause a program to hang as the program starts taking a lot of memory. This can lead to runtime errors. Therefore, make sure to include a condition that will terminate the loop.
     
  • Use built-in methods and libraries: Java has many built-in methods and libraries that can help you avoid runtime errors. Taking help from these libraries can save your day.  Therefore, use them instead of writing your own code whenever possible.
     
  • Test thoroughly: Testing is an essential step in any program writing. Test your program thoroughly to identify and fix any potential errors before deployment.

 

By following these best practices, you can avoid many common runtime errors in Java and make your code more reliable and stable.

Also check out - Phases of Compiler

Logical Error

Logical errors in Java occur when the code is syntactically correct but does not produce the expected output due to flawed logic.  These errors are not syntax errors, which are detected by the compiler, but rather errors in the design or implementation of the program. This is one of the most attention and logic based types of errors that a programmer encounters. These errors can be difficult to identify as they do not generate any error messages or exceptions. 

There are several types of logical errors in Java, including:

  • Misunderstanding operator precedence: It is important to have knowledge of order of precedence to avoid confusion and ambiguity. If a programmer misunderstands this order, they may end up with unexpected results. For example, if a programmer writes "x + y * z" instead of "(x + y) * z", the program will execute the multiplication before the addition, leading to incorrect results. 
     
  • Incorrect data types:Java is a strongly typed language, which means that variables must be declared with a specific data type. Here the program needs to know all the variable types at compilation. If a programmer uses the wrong data type, the program may not behave as intended. For example, if a programmer tries to add a String to an integer, the program will throw a runtime error.
     
  • Infinite loops: Infinite loops can handle the program. An infinite loop occurs when the condition of a loop never evaluates to false, causing the loop to execute indefinitely. This can occur if the programmer forgets to update the loop counter or if the loop condition is not defined correctly, that i always evaluates to true.

 

Must Read Static Blocks In Java.

Examples of Logical Errors

Here are some common types of logical errors in Java:

Example 1: Infinite Loops: This occurs when a loop does not have a terminating condition, causing it to run indefinitely. For example:

while (true) {
    System.out.println("Hello"); // prints "Hello" infinitely
}

 

Here, the logic written is wrong as there is a true in while loop which will make the loop run infinitely.  

Example 2: Incorrect Boolean Logic

int x = 5;
if (x > 10 || x < 0) {
    System.out.println("Invalid input"); // should not be printed
}

 

In the above code, the condition ‘x > 10 || x < 0’ will evaluate to false as ‘x’ is neither greater than 10 nor less than 0. The output "Invalid input" will not be printed due to incorrect boolean logic.

Example 3: Wrong Variable Assignment 

This occurs when a variable is assigned a value that does not match the intended value, leading to incorrect output. For example:

int a = 5;
String b = 10;
int c = a + b;
System.out.println("The sum of a and b is " + c); // prints "The sum of a and b is 510"

 

In the above code, the string concatenation operator "+" is used instead of the addition operator "+", leading to the incorrect output.

How to avoid Logical Errors

Avoiding logical errors in Java requires a good understanding of the language and programming concepts, careful planning, and thorough testing. Here are some tips to avoid logical errors in Java:

  • Plan your code: Take some time to plan and outline your code before you start writing it. 
     
  • Use meaningful variable names: Use variable names that are meaningful so it's easier to understand the purpose of the variables . Avoid using variables like a and b as they cause confusion.
     
  • Test your code: Test your code thoroughly to make sure it's working as expected.
     
  • Refactor your code: Refactor your code to make it more readable and maintainable. Use comments to explain what your code is doing.
     

By following these tips, you can avoid logical errors in Java and write more efficient and effective code.

Must Read What are Loops in Java.

Frequently Asked Questions

What is the best way to debug errors in Java?

The best way to debug all types of errors in Java is to use a good debugging tool. You should also use console log to help discover and fix errors. It's important to follow the order of code lines when debugging and to test each part of your code thoroughly to identify and fix errors.

What is a null pointer exception error in Java? 

A null pointer exception error occurs when a Java program attempts to reference to an object variable that is NULL(i.e., it does not point to any object). This results in a runtime error that crashes the program.

What is an array index out of bounds error in Java?

An array index out of bounds error in Java occurs when a program attempts to access an element of an array that is outside of the valid range of indices for that array. The valid range for the indices of the array is 0 to array.size()-1. 

Conclusion

We hope you have enjoyed reading this article. In conclusion, the three main types of errors in Java are syntax errors, runtime errors, and logical errors. Syntax errors occur when there is a mistake in the code structure, runtime errors occur during the execution of the program, and logical errors occur when the program does not produce the expected result.

Learn more, Types of information system

You can also consider reading our related articles like Exception HandlingGo Error HandlingThrow In JavaError Recovery and Handling etc.

Recommended Reading: 

Access modifiers in java

Previous article
Difference between Error and Exception
Next article
ClassNotFoundException in Java
Live masterclass