Compile time error java

This may sound awkward ... But I didn't understand it. Why do we have compile-time error and not compile-time exception in java ? I mean to say that we never say compile-time exception. We tend...

An error indicates that there is a problem with the program. An exception is a specific construct that interrupts the control flow of the program, and unwinds the stack, capturing information about the state of the stack so that it can be reported.

An exception can be used to indicate an error, but not always. For example:

void startOperation() {
 try {
  while (someComplexOperationIsOnGoing()) {
   checkRestart();
  }
 }
 catch (RestartException re) {
  startOperation();
 }
}

void checkRestart() {
 if (shouldRestart()) {
  throw new RestartException();
 }
}

This incomplete code sample is meant to show a case where an exception is not an error. This is not always best practice; but it is used in some cases where the intent is to interrupt the control flow deep in the program (such as redirecting the page in a web framework, when responding to an HTTP request) and return control to a higher-up level of the stack. The term exception refers to the mechanism which interrupts the program.

In java, there is an Exception class which encapsulates this behavior. The Error class also interrupts the control flow in the same way as an Exception; but it is reserved only for serious, unrecoverable problems that happen at runtime. It is used, for example, when the JVM runs out of memory and can’t create new objects.

The types of errors encountered when a software developer develops a Java application can be split into two broad categories: compile time errors and runtime errors. As the name implies, compile time errors occur when the code is built, but the program fails to compile. In contrast, Java runtime errors occur when a program successfully compiles but fails to execute.

If code doesn’t compile, the program is entirely unable to execute. As such, it’s imperative to fix compile time errors in Java as soon as they occur so that code can be pushed into an organization’s continuous delivery pipeline, run and tested.

Compile time errors in Java are a source of great frustration to developers, especially as they try to learn the language. Compile time error messages are notoriously unclear, and troubleshooting such errors can be overwhelming.

To help alleviate the frustrations that compile time error often evoke, let’s explore the most commonly encountered compile time errors in Java, and some quick ways to fix them.

Top 10 common Java compile errors and how to fix them

Here are the 10 most commonly encountered Java compile time errors:

  1. Java source file name mismatch
  2. Improper casing
  3. Mismatched brackets
  4. Missing semicolons
  5. Method is undefined
  6. Variable already defined
  7. Variable not initialized
  8. Type mismatch: cannot convert
  9. Return type required
  10. Unreachable code

Java compile error example: 'Unreachable code'

Example of an ‘unreachable code’ error, one of several common Java compile errors.

1. Class and source file mismatch

The name of the Java source file, as it resides on the filesystem, must exactly match the name of the public Java class as it is defined in the class declaration. If not, the compiler generates the following Java compile time error:

The public type problemcode must be defined in its own file

A Java class declaration looks like this:

public class ThisWillCompile { }

This Java class must be saved in a file named ThisWillCompile.java — or else it won’t compile.

Java provides no lenience here — the source filename must exactly match the name used in the class declaration. If the first letter of the file is lowercase but the class declaration is uppercase, the code will not compile. If an extra letter or number pads the name of the source file, the code will not compile.

Many developers who learn the language with a text editor and DOS prompt often run into this problem of name mismatches. Fortunately, modern IDEs, such as Eclipse and IntelliJ, are designed to keep the Java class and the underlying file name in sync.

2. Improper casing

When I first learned to code, nobody told me that Java was case-sensitive. I wasted untold hours as I tried to figure out why the code I meticulously copied from a study guide did not compile. My frustration was palpable when I learned letter casing can be the only difference between compiler success and coding failure.

The Java compiler treats uppercase and lowercase letters completely differently. «Public» is different from «public» which is different from «puBliC.» For example, this code will not compile:

Int x = 10;
system.out.println(x);

To make matters worse, the associated Java compile error poorly describes the source of the problem.

Int and system cannot be resolved to a type

To fix the problem, simply make the «I» in «Integer» lowercase and make the «s» in «system» uppercase:

int x = 10;
System.out.println(x);

Java’s stringency with upstyling and downstyling letters can frustrate coders who are new to the language. Nevertheless, casing of Java classes and variables means a great deal to other developers who read your code to understand what it does, or what it is supposed to do. As developers deepen their understanding of Java they appreciate the important nuance of properly cased code, such as the use of camel case and snake case.

3. Mismatched brackets

A mismatched brace or bracket is the bane of every programmer. Every open bracket in the code, be it a square bracket, curly bracket or round bracket, requires a matching and corresponding closed bracket.

Sometimes a programmer forgets the closing bracket for a method, or remembers to put in a closing bracket for a method but forgets to close the class. If the brackets don’t all match up, the result is a compile time error.

Not only is a mismatched bracket difficult to identify within a complex class or method, but the associated Java compile error can be outright misleading. For example, the following line of code is missing a round brace after the println:

int x = 10;
System.out.println x);

When the compiler attempts to build this code, it reports the following errors, neither of which properly describe the problem:

Duplicate local variable x
System.out cannot be resolved to a type

The fix to this compile error is to add a leading round bracket after the println to make the error go away:

int x = 10;
System.out.println (x);

One way to help troubleshoot mismatched brackets and braces is to format the code. Online lint tools do this, and most IDEs have built-in formatters. It is much easier to identify mismatched brackets and braces in formatted code.

4. Missing semicolons

Every statement in a Java program must end with a semicolon.

This strict requirement can trip up some developers who are familiar with other languages, such as JavaScript or Groovy, which do not require a semicolon at the end of every line of code.

Adding to potential confusion, not every line of Java code is a statement. A class declaration is not considered a statement, so it is not followed by a semicolon. Likewise, a method declaration also is not considered a statement and requires no semicolon.

Fortunately, the Java compiler can warn developers about a missing semicolon. Take a look at the following line of Java code:

System.out.println (x)

The Java compiler points directly at the problem:

Syntax error, insert ';' to complete Statement.

And the code below shows the semicolon is correctly added:

System.out.println (x);

5. Method is undefined

Another issue that often befuddles new developers is when and when not to use round brackets.

If round brackets are appended to a variable, the compiler thinks the code wants to invoke a method. The following code triggers a «method is not defined» compiler error:

int x();

Round braces are for methods, not variables. Removal of the braces eliminates the problem:

int x;

6. Variable is already defined

Developers can change the value of a variable in Java as many times as they like. That’s why it’s called a variable. But they can only declare and assign it a data-type once.

The following code will generate a «variable already defined» error:

int x = 10;
int x = 20;

Developers also can use the variable «x» multiple times in the code, but they can declare it as an int only once.

The following code eliminates the «variable already defined» error:

int x = 10;
x = 20;

7. Local variable not initialized

Can you tell what’s wrong with the following code?

int x ;
System.out.println (x);

Class and instance variables in Java are initialized to null or zero. However, a variable declared within a method does not receive a default initialization. Any attempt to use a method-level variable that has not been assigned a value will result in a «variable not initialized» error.

The lack of variable initialization is fixed in the code below:

int x = 0;
System.out.println (x);

8. Type mismatch

Java is a strongly typed language. That means a variable cannot switch from one type to another mid-method. Look at the following code:

int x = 0;
String square = x * x;

The String variable is assigned the result of an int multiplied by itself. The multiplication of an int results in an int, not a String. As a result, the Java compiler declares a type mismatch.

To fix the type mismatch compile error, use datatypes consistently throughout your application. The following code compiles correctly:

int x = 0;
int square = x * x;

9. Return type required

Every method signature specifies the type of data that is returned to the calling program. For example, the following method returns a String:

public String pointOfNoReturn() {
return "abcdefu";
}

If the method body does not return the appropriate type back to the calling program, this will result in an error: «This method must return a result of a type.»

There are two quick fixes to this error. To return nothing from the method, specify a void return type. Alternatively, to specify a return type in the method signature, make sure there is a return statement at the termination of the method.

10. Unreachable code

Poorly planned boolean logic within a method can sometimes result in a situation where the compiler never reaches the final lines of code. Here’s an example:

int x = 10;
if ( x < 10 ) {
return true;
}
else {
return false;
}
System.out.println("done!");

Notice that every possible pathway through the logic will be exhausted through either the if or the else block. The last line of code becomes unreachable.

To solve this Java compiler error, place the unreachable code in a position where it can execute before every logical pathway through the code is exhausted. The following revision to the code will compile without error:

int x = 10;
if ( x < 10 ) {
System.out.println("done!");
return true;
}
else {
System.out.println("done!");
return false;
}

Be patient with Java compile errors

It’s always frustrating when a developer pushes forward with features and enhancement, but progress is stifled by unexpected Java compile errors. A little patience and diligence — and this list of Java compile time errors and fixes — will minimize troubleshooting, and enable developers to more productively develop and improve software features.

Содержание

  1. Errors in Java | Runtime, Compile Time Errors
  2. Types of Errors in Java Programming
  3. Java Compile Time Errors
  4. Runtime Errors in Java
  5. Logical Errors in Java Program
  6. Runtime Errors in Java [SOLVED]
  7. Fix the 5 Most Common Types of Runtime Errors in Java
  8. What is a Runtime Error in Java?
  9. Differences Between Compile Time Error and Runtime Error in Java
  10. Why Runtime Error Occurs in Java ?
  11. Fix the top 10 most common compile time errors in Java
  12. Flummoxed why your Java code won’t compile? Here are the 10 most commonly encountered Java compile errors, along with the fixes that will get your code working in no time.
  13. 1. Class and source file mismatch
  14. 2. Improper casing
  15. 3. Mismatched brackets
  16. 4. Missing semicolons
  17. 5. Method is undefined
  18. 6. Variable is already defined
  19. 7. Local variable not initialized
  20. 8. Type mismatch
  21. 9. Return type required
  22. 10. Unreachable code

Errors in Java | Runtime, Compile Time Errors

Errors in Java occur when a programmer violates the rules of Java programming language.

It might be due to programmer’s typing mistakes while developing a program. It may produce incorrect output or may terminate the execution of the program abnormally.

For example, if you use the right parenthesis in a Java program where a right brace is needed, you have made a syntax error. You have violated the rules of Java language.

Therefore, it is important to detect and fix properly all errors occurring in a program so that the program will not terminate during execution.

Types of Errors in Java Programming

When we write a program for the first time, it usually contains errors. These errors are mainly divided into three types:

1. Compile-time errors (Syntax errors)
2. Runtime errors
3. Logical errors

Java Compile Time Errors

Compile-time errors occur when syntactical problems occur in a java program due to incorrect use of Java syntax.

These syntactical problems may be missing semicolons, missing brackets, misspelled keywords, use of undeclared variables, class not found, missing double-quote in Strings, and so on.

These problems occurring in a program are called syntax errors in Java.

When Java compiler finds syntax errors in a program, it prevents the code from compile successfully and will not create a .class file until errors are not corrected. An error message will be displayed on the console screen.

These errors must be removed by debugging before successfully compile and run the program. Let’s take an example program where we will get a syntax error.

Program source code 1:

When you will try to compile the above program, Java compiler will tell you where errors are in the program. Then you can go to the appropriate line, correct error, and recompile the program.

Let’s create a program where we will try to call the undeclared variable. In this case, we will get unresolved compilation problem.

Program source code 2:

Program source code 3: Missing parenthesis in for statement.

Program source code 4: Missing double quote in String literal.

We may also face another error related to the directory path. An error such as

means that you have not set the path correctly.

Runtime Errors in Java

Runtime errors occur when a program is successfully compiled creating the .class file but does not run properly. It is detected at run time (i.e. during the execution of the program).

Such a program that contains runtime errors, may produce wrong results due to wrong logic or terminate the program. These runtime errors are usually known as exceptions.

For example, if a user inputs a value of string type in a program but the computer is expecting an integer value, a runtime error will be generated.

The most common runtime errors are as follows:

1. Dividing an integer by zero.
2. Accessing an element that is out of range of the array.
3. Trying to store a value into an array that is not compatible type.
4. Passing an argument that is not in a valid range or valid value for a method.
5. Striving to use a negative size for an array.
6. Attempting to convert an invalid string into a number.
7. and many more.

When such errors are encountered in a program, Java generates an error message and terminates the program abnormally. To handle these kinds of errors during the runtime, we use exception handling technique in java program.

Let’s take different kinds of example programs to understand better. In this program, we will divide an integer number by zero. Java compiler cannot detect it.

Program source code 5:

The above program is syntactically correct. There is no syntax error and therefore, does not cause any problem during compilation. While executing, runtime error occurred that is not detected by compiler.

The error is detected by JVM only in runtime. Default exception handler displays an error message and terminates the program abnormally without executing further statements in the program.

Let’s take an example program where we will try to retrieve a value from an array using an index that is out of range of the array.

Program source code 6:

Logical Errors in Java Program

Logical errors in Java are the most critical errors in a program and they are difficult to detect. These errors occur when the programmer uses incorrect logic or wrong formula in the coding.

The program will be compiled and executed successfully but does not return the expected output.

Logical errors are not detected either by Java compiler or JVM (Java runtime system). The programmer is entirely responsible for them. They can be detected by application testers when they compare the actual result with its expected result.

For example, a programmer wants to print even numbers from an array but he uses division (/) operator instead of modulus (%) operator to get the remainder of each number. Due to which he got the wrong results.

Let’s see the following source code related to this problem.

Program source code 7:

As you can see the program is successfully compiled and executed but the programmer got the wrong output due to logical errors in the program.

Seldom does a program run successfully at its first attempt. A software engineer in a company also commits several errors while designing the project or developing code.

These errors in a program are also called bugs and the process of fixing these bugs is called debugging.

All modern integrated development environments (IDEs) such as Eclipse, NetBeans, JBuilder, etc provide a tool known as debugger that helps to run the program step by step to detect bugs.

If you need professional help with Java homework assignments online, please address experts from AssignmentCore to get your Java projects done with no errors.

In this tutorial, we have familiarized different types of errors in java that may possibly occur in a program.
Thanks for reading.
Next ⇒ Exception handling Interview Programs for Practice

Источник

Runtime Errors in Java [SOLVED]

While working with the programming languages like executing a software program, there are many instances that we run into issues due to the run time errors or compilation errors. All these errors occur when the application is running. You might come across an instance where the application acts differently in a negative way to the requirements, then it means that a runtime error took place.

As it is one of the most common type of error that occurs during a software executive, let us get a deep idea on how to fix common types of runtime errors in Java and also the steps to be taken to resolve them on a timely basis.

Fix the 5 Most Common Types of Runtime Errors in Java

What is a Runtime Error in Java?

A runtime error in Java is referred to as an application error that comes up during the execution process of the program. This runtime error usually takes place when the syntax is corrected as expected while the issue lies during the program execution. All these errors can be detected by JVM – Java Virtual Machine and cannot be identified during the compilation time. Java is one of the most sought-after programming languages for the hiring managers across the world. So become an expert in Java through our Java Training and grab the best job opportunity.

Now, In this post, Let us discuss the top runtime errors in Java.

  1. Division by zero errors
  2. IO errors
  3. Out of range errors
  4. Undefined object errors

Differences Between Compile Time Error and Runtime Error in Java

Compile time errors are those errors in which the syntax would be incorrect in the application code. An example would be like missing semicolons, parenthesis, incorrect keywords, usage of undeclared variables, etc.

The Java compiler is capable of detecting the syntax errors during the compile time and the error message will be appearing on the screen. The compiler is also capable of preventing the code from the execution unless and until the error is resolved. Therefore it is important that these errors are addressed by making the necessary changes before the program is successfully executed.

The runtime errors occur during the program execution after the compilation has completed. Any program that is throwing a runtime error means that there are no issues with Syntax in the program.

Why Runtime Error Occurs in Java ?

Below listed are the most common types of runtime errors that occur in Java.

  1. Accessing an element that is out of range in an array
  2. Dividing a number with 0
  3. Less space or insufficient space memory
  4. Conversion of an invalid string into a number
  5. Attempting to store an incompatible value to a collection

When you come across such an address, you need to know that the Java compiler will be generating an error message and the program gets terminated abnormally. Runtime errors do not require to be caught explicitly. It is useful if you catch the runtime errors and resolve them to complete the program execution.

Let us review a few of the most common runtime errors in Java programming with examples to gain a deeper understanding.

Источник

Fix the top 10 most common compile time errors in Java

Flummoxed why your Java code won’t compile? Here are the 10 most commonly encountered Java compile errors, along with the fixes that will get your code working in no time.

The types of errors encountered when a software developer develops a Java application can be split into two broad categories: compile time errors and runtime errors. As the name implies, compile time errors occur when the code is built, but the program fails to compile. In contrast, Java runtime errors occur when a program successfully compiles but fails to execute.

If code doesn’t compile, the program is entirely unable to execute. As such, it’s imperative to fix compile time errors in Java as soon as they occur so that code can be pushed into an organization’s continuous delivery pipeline, run and tested.

Compile time errors in Java are a source of great frustration to developers, especially as they try to learn the language. Compile time error messages are notoriously unclear, and troubleshooting such errors can be overwhelming.

To help alleviate the frustrations that compile time error often evoke, let’s explore the most commonly encountered compile time errors in Java, and some quick ways to fix them.

Here are the 10 most commonly encountered Java compile time errors:

  1. Java source file name mismatch
  2. Improper casing
  3. Mismatched brackets
  4. Missing semicolons
  5. Method is undefined
  6. Variable already defined
  7. Variable not initialized
  8. Type mismatch: cannot convert
  9. Return type required
  10. Unreachable code

Example of an ‘unreachable code’ error, one of several common Java compile errors.

1. Class and source file mismatch

The name of the Java source file, as it resides on the filesystem, must exactly match the name of the public Java class as it is defined in the class declaration. If not, the compiler generates the following Java compile time error:

A Java class declaration looks like this:

This Java class must be saved in a file named ThisWillCompile.java — or else it won’t compile.

Java provides no lenience here — the source filename must exactly match the name used in the class declaration. If the first letter of the file is lowercase but the class declaration is uppercase, the code will not compile. If an extra letter or number pads the name of the source file, the code will not compile.

Many developers who learn the language with a text editor and DOS prompt often run into this problem of name mismatches. Fortunately, modern IDEs, such as Eclipse and IntelliJ, are designed to keep the Java class and the underlying file name in sync.

2. Improper casing

When I first learned to code, nobody told me that Java was case-sensitive. I wasted untold hours as I tried to figure out why the code I meticulously copied from a study guide did not compile. My frustration was palpable when I learned letter casing can be the only difference between compiler success and coding failure.

The Java compiler treats uppercase and lowercase letters completely differently. «Public» is different from «public» which is different from «puBliC.» For example, this code will not compile:

To make matters worse, the associated Java compile error poorly describes the source of the problem.

To fix the problem, simply make the «I» in «Integer» lowercase and make the «s» in «system» uppercase:

Java’s stringency with upstyling and downstyling letters can frustrate coders who are new to the language. Nevertheless, casing of Java classes and variables means a great deal to other developers who read your code to understand what it does, or what it is supposed to do. As developers deepen their understanding of Java they appreciate the important nuance of properly cased code, such as the use of camel case and snake case.

3. Mismatched brackets

A mismatched brace or bracket is the bane of every programmer. Every open bracket in the code, be it a square bracket, curly bracket or round bracket, requires a matching and corresponding closed bracket.

Sometimes a programmer forgets the closing bracket for a method, or remembers to put in a closing bracket for a method but forgets to close the class. If the brackets don’t all match up, the result is a compile time error.

Not only is a mismatched bracket difficult to identify within a complex class or method, but the associated Java compile error can be outright misleading. For example, the following line of code is missing a round brace after the println :

When the compiler attempts to build this code, it reports the following errors, neither of which properly describe the problem:

The fix to this compile error is to add a leading round bracket after the println to make the error go away:

One way to help troubleshoot mismatched brackets and braces is to format the code. Online lint tools do this, and most IDEs have built-in formatters. It is much easier to identify mismatched brackets and braces in formatted code.

4. Missing semicolons

Every statement in a Java program must end with a semicolon.

This strict requirement can trip up some developers who are familiar with other languages, such as JavaScript or Groovy, which do not require a semicolon at the end of every line of code.

Adding to potential confusion, not every line of Java code is a statement. A class declaration is not considered a statement, so it is not followed by a semicolon. Likewise, a method declaration also is not considered a statement and requires no semicolon.

Fortunately, the Java compiler can warn developers about a missing semicolon. Take a look at the following line of Java code:

The Java compiler points directly at the problem:

And the code below shows the semicolon is correctly added:

5. Method is undefined

Another issue that often befuddles new developers is when and when not to use round brackets.

If round brackets are appended to a variable, the compiler thinks the code wants to invoke a method. The following code triggers a «method is not defined» compiler error:

Round braces are for methods, not variables. Removal of the braces eliminates the problem:

6. Variable is already defined

Developers can change the value of a variable in Java as many times as they like. That’s why it’s called a variable. But they can only declare and assign it a data-type once.

The following code will generate a «variable already defined» error:

Developers also can use the variable » x » multiple times in the code, but they can declare it as an int only once.

The following code eliminates the «variable already defined» error:

7. Local variable not initialized

Can you tell what’s wrong with the following code?

Class and instance variables in Java are initialized to null or zero. However, a variable declared within a method does not receive a default initialization. Any attempt to use a method-level variable that has not been assigned a value will result in a «variable not initialized» error.

The lack of variable initialization is fixed in the code below:

8. Type mismatch

Java is a strongly typed language. That means a variable cannot switch from one type to another mid-method. Look at the following code:

The String variable is assigned the result of an int multiplied by itself. The multiplication of an int results in an int , not a String . As a result, the Java compiler declares a type mismatch.

To fix the type mismatch compile error, use datatypes consistently throughout your application. The following code compiles correctly:

9. Return type required

Every method signature specifies the type of data that is returned to the calling program. For example, the following method returns a String :

If the method body does not return the appropriate type back to the calling program, this will result in an error: «This method must return a result of a type.»

There are two quick fixes to this error. To return nothing from the method, specify a void return type. Alternatively, to specify a return type in the method signature, make sure there is a return statement at the termination of the method.

10. Unreachable code

Poorly planned boolean logic within a method can sometimes result in a situation where the compiler never reaches the final lines of code. Here’s an example:

Notice that every possible pathway through the logic will be exhausted through either the if or the else block. The last line of code becomes unreachable.

To solve this Java compiler error, place the unreachable code in a position where it can execute before every logical pathway through the code is exhausted. The following revision to the code will compile without error:

It’s always frustrating when a developer pushes forward with features and enhancement, but progress is stifled by unexpected Java compile errors. A little patience and diligence — and this list of Java compile time errors and fixes — will minimize troubleshooting, and enable developers to more productively develop and improve software features.

Источник

Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. 

The most common errors can be broadly classified as follows:

1. Run Time Error: 

Run Time errors occur or we can say, are detected during the execution of the program. Sometimes these are discovered when the user enters an invalid data or data which is not relevant. Runtime errors occur when a program does not contain any syntax errors but asks the computer to do something that the computer is unable to reliably do. During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) that detects it while the program is running. To handle the error during the run time we can put our error code inside the try block and catch the error inside the catch block. 

For example: if the user inputs a data of string format when the computer is expecting an integer, there will be a runtime error. Example 1: Runtime Error caused by dividing by zero 

Java

class DivByZero {

    public static void main(String args[])

    {

        int var1 = 15;

        int var2 = 5;

        int var3 = 0;

        int ans1 = var1 / var2;

        int ans2 = var1 / var3;

        System.out.println(

            "Division of va1"

            + " by var2 is: "

            + ans1);

        System.out.println(

            "Division of va1"

            + " by var3 is: "

            + ans2);

    }

}

Runtime Error in java code:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at DivByZero.main(File.java:14)

Example 2: Runtime Error caused by Assigning/Retrieving Value from an array using an index which is greater than the size of the array 

Java

class RTErrorDemo {

    public static void main(String args[])

    {

        int arr[] = new int[5];

        arr[9] = 250;

        System.out.println("Value assigned! ");

    }

}

RunTime Error in java code:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at RTErrorDemo.main(File.java:10)

2. Compile Time Error: 

Compile Time Errors are those errors which prevent the code from running because of an incorrect syntax such as a missing semicolon at the end of a statement or a missing bracket, class not found, etc. These errors are detected by the java compiler and an error message is displayed on the screen while compiling. Compile Time Errors are sometimes also referred to as Syntax errors. These kind of errors are easy to spot and rectify because the java compiler finds them for you. The compiler will tell you which piece of code in the program got in trouble and its best guess as to what you did wrong. Usually, the compiler indicates the exact line where the error is, or sometimes the line just before it, however, if the problem is with incorrectly nested braces, the actual error may be at the beginning of the block. In effect, syntax errors represent grammatical errors in the use of the programming language. 

Example 1: Misspelled variable name or method names 

Java

class MisspelledVar {

    public static void main(String args[])

    {

        int a = 40, b = 60;

        int Sum = a + b;

        System.out.println(

            "Sum of variables is "

            + sum);

    }

}

Compilation Error in java code:

prog.java:14: error: cannot find symbol
            + sum);
              ^
  symbol:   variable sum
  location: class MisspelledVar
1 error

Example 2: Missing semicolons 

Java

class PrintingSentence {

    public static void main(String args[])

    {

        String s = "GeeksforGeeks";

        System.out.println("Welcome to " + s)

    }

}

Compilation Error in java code:

prog.java:8: error: ';' expected
        System.out.println("Welcome to " + s)
                                             ^
1 error

Example: Missing parenthesis, square brackets, or curly braces 

Java

class MissingParenthesis {

    public static void main(String args[])

    {

        System.out.println("Printing 1 to 5 n");

        int i;

        for (i = 1; i <= 5; i++ {

            System.out.println(i + "n");

        }

    }

}

Compilation Error in java code:

prog.java:10: error: ')' expected
        for (i = 1; i <= 5; i++ {
                               ^
1 error

Example: Incorrect format of selection statements or loops 

Java

class IncorrectLoop {

    public static void main(String args[])

    {

        System.out.println("Multiplication Table of 7");

        int a = 7, ans;

        int i;

        for (i = 1, i <= 10; i++) {

            ans = a * i;

            System.out.println(ans + "n");

        }

    }

}

Compilation Error in java code:

prog.java:12: error: not a statement
        for (i = 1, i <= 10; i++) {
                      ^
prog.java:12: error: ';' expected
        for (i = 1, i <= 10; i++) {
                                ^
2 errors

Logical Error: A logic error is when your program compiles and executes, but does the wrong thing or returns an incorrect result or no output when it should be returning an output. These errors are detected neither by the compiler nor by JVM. The Java system has no idea what your program is supposed to do, so it provides no additional information to help you find the error. Logical errors are also called Semantic Errors. These errors are caused due to an incorrect idea or concept used by a programmer while coding. Syntax errors are grammatical errors whereas, logical errors are errors arising out of an incorrect meaning. For example, if a programmer accidentally adds two variables when he or she meant to divide them, the program will give no error and will execute successfully but with an incorrect result. 

Example: Accidentally using an incorrect operator on the variables to perform an operation (Using ‘/’ operator to get the modulus instead using ‘%’) 

Java

public class LErrorDemo {

    public static void main(String[] args)

    {

        int num = 789;

        int reversednum = 0;

        int remainder;

        while (num != 0) {

            remainder = num / 10;

            reversednum

                = reversednum * 10

                  + remainder;

            num /= 10;

        }

        System.out.println("Reversed number is "

                           + reversednum);

    }

}

Output:

Reversed number is 7870

Example: Displaying the wrong message 

Java

class IncorrectMessage {

    public static void main(String args[])

    {

        int a = 2, b = 8, c = 6;

        System.out.println(

            "Finding the largest number n");

        if (a > b && a > c)

            System.out.println(

                a + " is the largest Number");

        else if (b > a && b > c)

            System.out.println(

                b + " is the smallest Number");

        else

            System.out.println(

                c + " is the largest Number");

    }

}

Output:

Finding the largest number 

8 is the smallest Number

Syntax Error:

Syntax and Logical errors are faced by Programmers.

Spelling or grammatical mistakes are syntax errors, for example, using an uninitialized variable, using an undefined variable, etc., missing a semicolon, etc.

int x, y;
x = 10 // missing semicolon (;)
z = x + y; // z is undefined, y in uninitialized.

Syntax errors can be removed with the help of the compiler.

Errors in Java occur when a programmer violates the rules of Java programming language.

It might be due to programmer’s typing mistakes while developing a program. It may produce incorrect output or may terminate the execution of the program abnormally.

For example, if you use the right parenthesis in a Java program where a right brace is needed, you have made a syntax error. You have violated the rules of Java language.

Therefore, it is important to detect and fix properly all errors occurring in a program so that the program will not terminate during execution.

Types of Errors in Java Programming


When we write a program for the first time, it usually contains errors. These errors are mainly divided into three types:

1. Compile-time errors (Syntax errors)
2. Runtime errors
3. Logical errors

Types of errors in Java programming


Compile-time errors occur when syntactical problems occur in a java program due to incorrect use of Java syntax.

These syntactical problems may be missing semicolons, missing brackets, misspelled keywords, use of undeclared variables, class not found, missing double-quote in Strings, and so on.

These problems occurring in a program are called syntax errors in Java.

Since all syntax errors are detected by Java compiler, therefore, these errors are also known as compile time errors in Java.

When Java compiler finds syntax errors in a program, it prevents the code from compile successfully and will not create a .class file until errors are not corrected. An error message will be displayed on the console screen.

These errors must be removed by debugging before successfully compile and run the program. Let’s take an example program where we will get a syntax error.

Program source code 1:

public class CompileTimeErrorEx 
{
public static void main(String[] args) 
{
  System.out.println("a") // Syntax error. Semicolon missing.
 }
}
Compile time error in Java code:
      Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
      Syntax error, insert ";" to complete BlockStatements

When you will try to compile the above program, Java compiler will tell you where errors are in the program. Then you can go to the appropriate line, correct error, and recompile the program.

Let’s create a program where we will try to call the undeclared variable. In this case, we will get unresolved compilation problem.

Program source code 2:

public class MisspelledVar 
{	
public static void main(String[] args) 
{
int x = 20, y = 30;

// Declare variable sum.
   int sum = x + y; 

// Call variable Sum with Capital S.
   System.out.println("Sum of two numbers: " + Sum); // Calling of undeclared variable.
 }
}
Compile time error in Java code:
       Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Sum cannot be resolved to a variable

Program source code 3: Missing parenthesis in for statement.

public class MissingBracket 
{	
public static void main(String[] args) 
{ 
 int i; 
 int sum = 0;

// Missing bracket in for statement.
 for (i = 1; i <= 5; i++ // insert " ) Statement" to complete For Statement.
 {
   sum = sum + i;	
 }
System.out.println("Sum of 1 to 5 n");
System.out.println(sum); 
  }
}
Compile time error in Java code:
      Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
      Syntax error, insert ") Statement" to complete ForStatement

Program source code 4: Missing double quote in String literal.

public class MissingDoubleQuote
{	
public static void main(String[] args) 
{ 
 String str = "Scientech; // Missing double quote in String literal.
 System.out.println(str);
  }
}
Compile time error in Java code:
       Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	String literal is not properly closed by a double-quote

We may also face another error related to the directory path. An error such as

javac : command not found

means that you have not set the path correctly.

Runtime Errors in Java


Runtime errors occur when a program is successfully compiled creating the .class file but does not run properly. It is detected at run time (i.e. during the execution of the program).

Java compiler has no technique to detect runtime errors during compilation because a compiler does not have all of the runtime information available to it. JVM is responsible to detect runtime errors while the program is running.

Such a program that contains runtime errors, may produce wrong results due to wrong logic or terminate the program. These runtime errors are usually known as exceptions.

For example, if a user inputs a value of string type in a program but the computer is expecting an integer value, a runtime error will be generated.

The most common runtime errors are as follows:

1. Dividing an integer by zero.
2. Accessing an element that is out of range of the array.
3. Trying to store a value into an array that is not compatible type.
4. Passing an argument that is not in a valid range or valid value for a method.
5. Striving to use a negative size for an array.
6. Attempting to convert an invalid string into a number.
7. and many more.

When such errors are encountered in a program, Java generates an error message and terminates the program abnormally. To handle these kinds of errors during the runtime, we use exception handling technique in java program.

Let’s take different kinds of example programs to understand better. In this program, we will divide an integer number by zero. Java compiler cannot detect it.

Program source code 5:

public class DivisionByZeroError
{	
public static void main(String[] args) 
{ 
 int a = 20, b = 5, c = 5;
 int z = a/(b-c); // Division by zero.
 
 System.out.println("Result: " +z);
  }
}
Output:
       Exception in thread "main" java.lang.ArithmeticException: / by zero
	at errorsProgram.DivisionByZeroError.main(DivisionByZeroError.java:8)

The above program is syntactically correct. There is no syntax error and therefore, does not cause any problem during compilation. While executing, runtime error occurred that is not detected by compiler.

The error is detected by JVM only in runtime. Default exception handler displays an error message and terminates the program abnormally without executing further statements in the program.

Let’s take an example program where we will try to retrieve a value from an array using an index that is out of range of the array.

Program source code 6: 

public class AccessingValueOutOfRangeError
{	
public static void main(String[ ] args) 
{ 
 int arr[ ] = {1, 2, 3, 4, 5}; // Here, array size is 5.
 System.out.println("Value at 5th position: "+arr[5]);
 }
}
Output:
       Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
	at errorsProgram.AccessingValueOutOfRangeError.main(AccessingValueOutOfRangeError.java:9)

Logical Errors in Java Program


Logical errors in Java are the most critical errors in a program and they are difficult to detect. These errors occur when the programmer uses incorrect logic or wrong formula in the coding.

The program will be compiled and executed successfully but does not return the expected output.

Logical errors are not detected either by Java compiler or JVM (Java runtime system). The programmer is entirely responsible for them. They can be detected by application testers when they compare the actual result with its expected result.

For example, a programmer wants to print even numbers from an array but he uses division (/) operator instead of modulus (%) operator to get the remainder of each number. Due to which he got the wrong results.

Let’s see the following source code related to this problem.

Program source code 7:

public class LogicalErrorEx
{	
public static void main(String[] args) 
{ 
 int a[]={1, 2 , 5, 6, 3, 10, 12, 13, 14};  
 
System.out.println("Even Numbers:");  
for(int i = 0; i <a.length; i++)
{  
if(a[i] / 2 == 0) // Using wrong operator.
{  
  System.out.println(a[i]);  
 }  
}  
 }
}
Output:
       Even Numbers:
       1

As you can see the program is successfully compiled and executed but the programmer got the wrong output due to logical errors in the program.


Seldom does a program run successfully at its first attempt. A software engineer in a company also commits several errors while designing the project or developing code.

These errors in a program are also called bugs and the process of fixing these bugs is called debugging.

All modern integrated development environments (IDEs) such as Eclipse, NetBeans, JBuilder, etc provide a tool known as debugger that helps to run the program step by step to detect bugs.


If you need professional help with Java homework assignments online, please address experts from AssignmentCore to get your Java projects done with no errors.

In this tutorial, we have familiarized different types of errors in java that may possibly occur in a program.
Thanks for reading!!!
Next ⇒ Exception handling Interview Programs for Practice

⇐ Prev Next ⇒

A «compile-time» error is one which prevents your code from compiling. This page describes 14 of the most common errors you will encounter. Compile-time errors are divided into three categories:

  1. Lexical: These generally occur when you include disallowed characters in your code (e.g. int #people = 10;).
  2. Syntactical: These occur when your code is «out of order» (e.g. for (int i=0; i++; i<10)).
  3. Semantic: These occur when the meaning of your code is unclear (e.g. two variables with the same name).

Note that the exact wording of these errors may vary, depending on which development environment you are using.

Errors described on this page (click to jump to that error):

  1. Cannot return a value from a method of type void
  2. ‘Class’ or ‘interface’ expected
  3. Class should be delcared abstract; it does not define…
  4. Else without if
  5. Expected: ;, {, }, (, or )
  6. Identifier expected / Illegal character
  7. Incompatible types / Inconvertible types (cannot cast)
  8. Method does not return a value / Missing return statement
  9. Method not found
  10. Not a statement
  11. Return type required
  12. Unreachable statement
  13. Variable already defined
  14. Variable not declared

Cannot return a value from a method of type void

When a method is declared as having a return type of void, it cannot contain any return statements which return a value (it can, however, contain a return statement by itself, which will simply end the execution of the method). This problem is usually caused by accidentally making a method be of type void when it shouldn’t be or by accidentally including a return statement where there shouldn’t be one.

Example 1: Incorrect Code Example 1: Fixed Code

This method has a return type of void and so it may not return any values.

We change the return type of this method in order to fix the problem.

01  public void getName()
02  {   return this.name;
03  }
01  public String getName()
02  {   return this.name;
03  }


‘Class’ or ‘interface’ expected

This error will most likely be caused when you omit the keyword class or interface, as seen in the example below.

Example 1: Incorrect Code Example 1: Fixed Code

Here, we do not have either keyword present.

We add in class or interface, depending on our intentions within the program.

01  public Test
02  {
03      public void someMethod()
04      {   System.out.println("Hello, world!");
05      }
06  }
01  public class Test
02  {
03      public void someMethod()
04      {   System.out.println("Hello, world!");
05      }
06  }

— OR —

01  public interface Test
02  {
03      public void someMethod();
04  }

Class should be delcared abstract; it does not define…

This error arises when implementing an interface. Recall that when you say implements SomeInterface for a certain class, you guarantee that you have written all of the methods specified within that interface. If you are missing at least one of the methods which is listed in the interface, Java will not let your code compile.

As an example, consider an interface TestInterface which looks like:

public interface TestInterface
{
  public int methodOne();
  public String methodTwo(String z);
  public boolean methodThree();
}

Using TestInterface, consider the following example.

Example 1: Incorrect Code Example 1: Fixed Code

We receive an error message in this case because we implement TestInterface but do not include methodThree().

To allow this program to compile, we add in a «stub» for the required method. This is the quick way around the problem: in most cases, you will want to actually write a method body for this method so that it does what it was intended to do.

01  public class Test implements TestInterface
02  {
03      private int y = 700;
04  
05      public int methodOne()
06      {   int x = this.y - 1;
07          return x;
08      }
09  
10      public String methodTwo(String z)
11      {   String label = "Val: " + z;
12          return label;
13      }
14  }
01  public class Test implements TestInterface
02  {
03      private int y = 700;
04  
05      public int methodOne()
06      {   int x = this.y - 1;
07          return x;
08      }
09  
10      public String methodTwo(String z)
11      {   String label = "Val: " + z;
12          return label;
13      }
14
15      public boolean methodThree()
16      {   return false;
17      }
18  }

Note that when you are implementing methods in the interface, the method signatures must match exactly. That is, if the interface expects that you implement a method public String longer(String a, String b), then you must write a method with exactly the same name, exactly the same return type, and exactly the same parameters (in this case, two Strings).


Else without if

This error occurs when you have an else or else if clause without an if clause above it. This is most likely because you have accidentally forgotten/added extra { or } braces, or you have placed an else clause in the wrong place, as illustrated in the example below. The key idea is that every else clause needs to have an associated if clause which occurs before it.

Example 1: Incorrect Code Example 1: Fixed Code

Here, we have accidentally placed the else clause within the if clause.

We place the else clause after the if clause, which correctly associates them.

01  String text = "abaaba";
02    
03  if (text.length() >= 6)
04  {   text += text;    
05  else
06  {   text += text.substring(3);
07  }
08  }
01  String text = "abaaba";
02    
03  if (text.length() >= 6)
04  {   text += text;
05      
06  }
07  else
08  {   text += text.substring(3);
09  }

Expected: ;, {, }, (, or )

Java is very specific about use of characters such as semicolons, brackets, or braces. Forgetting a semicolon is the simplest of these errors, and is fixed by placing a semicolon at the end of the line which causes the error. Brackets can be more complicated, because you may have to read through several nested if statements or loops in order to make sure that all brackets «match up» with each other properly. This is one of the reasons why indenting your code properly is a good idea.

Example 1: Incorrect Code Example 1: Fixed Code

Here, lines 6, 7, and 10 will give us compile-time errors because we have forgot to include brackets, a semicolon, and a close-brace respectively.

We add these in to fix the problems.

01  public class Test
02  { 
03      public void getName()
04      {   int k = 10;  
05    
06          if k == 10
07          { k++
08          }
09      }
10
01  public class Test
02  { 
03      public void getName()
04      {   int k = 10;  
05    
06          if (k == 10)
07          { k++;
08          }
09      }
10  }

Identifier expected / Illegal character

An identifier is another term for a variable. In Java, every variable name must begin with a letter/underscore and can then have any combination of letters, numbers, and underscores. The example below illustrates two cases you may run into.

Example 1: Incorrect Code Example 1: Fixed Code

The variable name 10Names is not allowed because it begins with a number. The variable name wtPer#ofPeople is not allowed bacause it contains a pound sign.

To fix this, we change these to valid variable names.

01  private String[] 10Names;
02  private int wtPer#ofPeople;
01  private String[] tenNames;
02  private int wtPerNumberOfPeople;


Incompatible types / Inconvertible types (cannot cast)

In a Java assignment statement, the type of the variable on the left hand side must be the same as the type of the variable on the right hand side (or it needs to be able to be cast first in order to make it work). The example below would give three ‘incompatible types’ error messages.

Example 1: Incorrect Code Example 1: Fixed Code

Lines 5, 6, and 7 all give us errors. This is because an int cannot be assigned to a String, a boolean cannot be assigned to an int, and a String cannot be assigned to a boolean, respectively.

We change these three statements so that the primitive type / Object type is the same on both sides of the assignment (=) sign.

01  String theAge = "Twenty-two";
02  int x = 22;
03  boolean b = false;
04    
05  theAge = x;
06  x = b;
07  b = theAge;
01  String theAge = "Twenty-two";
02  int x = 22;
03  boolean b = false;
04    
05  theAge = "Thirty-three";
06  x = 33;
07  b = true;

Note that one common exception to this rule is that an int value can be assigned to a char value and vice-versa (this is because every character is actually represented as an integer ASCII value).

This error may also occur when trying to pass a value of one type into a method which expects another. An example of this is below.

Example 2: Incorrect Code Example 2: Fixed Code

Here, we try to pass a String as an actual parameter into a method which has an int as its formal parameter (these two types are incompatible).

To fix this, we change the type of the variable which is being passed. Alternately, we could have also changed the type of the actual parameter to be a String and then re-coded the method calcNewAge accordingly.

01  String theAge = "Twenty-two";
02  int result = calcNewAge(theAge);
03  
04  public int calcNewAge(int theAge)
05  {   return theAge / 2 + 7;
06  }
01  int theAge = 22;
02  int result = calcNewAge(theAge);
03  
04  public int calcNewAge(int theAge)
05  {   return theAge / 2 + 7;
06  }

You may also get a similar error if you are attempting to cast incorrectly. Recall that a primitive type may not be cast to an object or vice-versa. When casting between two objects, recall that object «A» may be cast to be of the same type as object «B» only if B’s class extends A’s class. As an example, consider a class Cat which extends the class Animal.

Example 3: Incorrect Code Example 3: Fixed Code

Here, lines 2 and 3 are incorrect attempts at casting because neither Animal nor String are subclasses of Cat.

Line 2 is a correct cast because Cat is a subclass of Animal (a Cat is an Animal, but an Animal is not necessarily a Cat).

01  Cat c = new Cat("Sparky", "black");
02  Animal a = (Animal) c;
03  String theCat = (String) c;
01  Animal a = new Animal("Sparky");
02  Cat c = (Cat) a;

Method does not return a value / Missing return statement

In Java, every method which does not have a return type of void must have at least one return statement.

Example 1: Incorrect Code Example 1: Fixed Code

The return type of this method is String, so Java expects that we have a return statement which returns a value with this type. As written, this method does not return anything.

Instead of printing these values to the screen, we return them.

01  public String getFortune()
02  {   if (this.age >= 19)
03      {   System.out.println("Good times ahead");
04      } 
05      else
06      {   System.out.println("Hailstorms unavoidable");
07      }
08  }
01  public String getFortune()
02  {   if (this.age >= 19)
03      {   return "Good times ahead";
04      } 
05      else
06      {   return "Hailstorms unavoidable";
07      }
08  }

This compile-time error can have a very subtle point which is often overlooked. If the return type of a method is not void, Java needs to ensure that the method will return a value in every possible case. That is, if all of your return statements are nested within if statements, Java will disallow the compilation process to continue because there is a chance that no return statement will be reached. The example below illustrates this.

Example 2: Incorrect Code Example 2: Fixed Code

In this example, we get a compile-time error because Java sees a possibility of this method not returning a value (if this.age is 99, for example).

To fix this, we ensure that the method will return a value in all possible cases by adding an else clause.

01  public String chatMethod()
02  {   if (this.age <= 18)
03      {   return "MSN";
04      } 
05      else if (this.age > 19 && this.age <= 30)
06      {   return "ICQ";
07      }
08  }

01  public String chatMethod()
02  {   if (this.age <= 18)
03      {   return "MSN";
04      } 
05      else if (this.age > 19 && this.age <= 30)
06      {   return "ICQ";
07      }
08      else
09      {   return "BBS";
10      }
11  }

Note that an easy way to «fix» this error is to simply add a meaningless return statement at the end of the method, such as return -1; or return null;. This often leads to problems elsewhere, such as causing the method to return unintended values.


Method not found

In Java, recall that a method’s signature consists of the method’s name and the types of its actual parameters. For example, the method public void move(int howFar) has the signature move(int). When a method call is made, a method with a signature exactly matching that of the method call must exist (e.g. the method name, the number of parameters, and the types of all parameters must match exactly). This error is illustrated below.

Example 1: Incorrect Code Example 1: Fixed Code

Line 3 calls a method which has signature larger(String, String). However, the method at line 5 has signature larger(int, int). These two signatures do not match (e.g. there exists no method with signature larger(String, String)), so an error is produced.

To fix this, we can modify the larger so that it has a matching signature to our method call. Alternately, we could have left the current method alone and written another (overloaded) method with the appropriate signature.

01  String first = "CN Tower";
02  String second = "Calgary Tower";
03  String res = this.larger(first, second);
04  
05  public int larger(int a, int b)
06  {   if (a > b)
07      {   return a;
08      } else
09      {   return b;
10      }
11  }
01  String first = "CN Tower";
02  String second = "Calgary Tower";
03  String res = this.larger(first, second);
04  
05  public String larger(String a, String b)
06  {   if (a.length() > b.length())
07      {   return a;
08      } else
09      {   return b;
10      }
11  }

Also note that this error may occur if you do not have the correct import statements at the top of your class.


Not a statement

Each line of Java code must have some sort of meaningful purpose. The compile-time error «not a statement» is usually the result of typing only part of a statement, leaving it incomplete and meaningless. One example of how this may occur (there are many) is seen below. In general, asking yourself «what was I trying to do with this line of code?» is sufficient to fix the problem.

Example 1: Incorrect Code Example 1: Fixed Code

Line 5 will cause the error in this case, as the line grades[1]; is completely meaningless by itself, as it does not give any instruction to the compiler.

We change this line to be a valid, meaningful statement («set the value of x to be the value of the array grades at element 1″). This is just one possible way of fixing the problem (it depends on how you intend things to work).

01  int grades[] = new int[2];
02  int x;
03  grades[0] = 96;
04  grades[1] = 93;
05  grades[1];
06  System.out.println(x);

01  int grades[] = new int[2];
02  int x;
03  grades[0] = 96;
04  grades[1] = 93;
05  x = grades[1];
06  System.out.println(x);

Return type required

For each method, Java requires a return type (e.g. String, int, boolean). Note that void is also considered to be a «return type» even though a method with a void return type does not return a value.

Example 1: Incorrect Code Example 1: Fixed Code

An error is caused because the theAnswer() method does not have a declared return type.

Two possible solutions to this problem are suggested (each would depend on the context of how the method is to be actually used in your program).

01  private theAnswer()
02  {   System.out.println("42");
03  }
01  private void theAnswer()
02  {   System.out.println("42");
03  }

— OR —

01  private int theAnswer()
02  {   return 42;
03  }

Unreachable statement

This error usually occurs if you have a statement placed directly after a return statement. Since Java executes code line-by-line (unless a method call is made), and since a return statement causes the execution of the program to break out of that method and return to the caller, then anything placed directly after a return statement will never be reached.

Example 1: Incorrect Code Example 1: Fixed Code

Line 4 is directly after a return statement, so it cannot be reached because the method will end at line 3.

We switch lines 3 and 4 to ensure that nothing is after the return statement.

01  public String oneMoreA(String orig)
02  {   String newStr = orig + "A";
03      return newStr;
04      this.counter++;
05  }
01  public String oneMoreA(String orig)
02  {   String newStr = orig + "A";
03      this.counter++;

04      return newStr;
05  }

You (may) also get this error if you place a statement outside of a method, which could be the result of { and } braces not being matched up properly.


Variable already defined

This compile-time error is typically caused by a programmer attempting to declare a variable twice. Recall that a statment such as int temp; declares the variable named temp to be of type int. Once this declaration has been made, Java can refer to this variable by its name (e.g. temp = 15;) but does not let the programmer declare it a second time by including the variable type before the name, as seen in the example below.

Example 1: Incorrect Code Example 1: Fixed Code

Here, we have declared the variable temperature twice: once at line 3 and then again at line 6.

We have fixed the problem by only declaring the variable once (at line 3) and we refer only to the variable’s name on line 6.

01  int a = 7;
02  int b = 12;
03  int temperature = Math.max(a, b);
04    
05  if (temperature > 10)
06  {   int temperature = 0;
07  }
01  int a = 7;
02  int b = 12;
03  int temperature = Math.max(a, b);
04    
05  if (temperature > 10)
06  {   temperature = 0;
07  }

You may also get this error if you have tried to declare two variables of different types using the same variable name (in Java, every variable must have a unique name). The example below illustrates this using two variables of type int and String.

Example 2: Incorrect Code Example 2: Fixed Code

Here we are trying to declare two variables using the same variable name of temperature. This is not allowed, regardless of the types of the variables.

We fix the problem by ensuring that each variable has a unique name.

01  int temperature = 22;
02  String temperature = "Hot Outside";
01  int temperature = 22;
02  String tempDescription = "Hot Outside";

The only time where repetition of variable names or declarations are allowed is if the two variables are in different scopes. Recall that the scope of a variable is determined by the set of braces, { and }, in which it is enclosed. This is illustrated in the two examples below.

Example 3: Correct Code Example 4: Correct Code

This is allowed because the delarations on lines 4 and 7 are being done within different scopes. One is within the scope of the if statement, and the other is within the scope of the else if statement.

Similarly, this is also allowed because temp is declared in two different methods and will therefore be done within different scopes.

01  int temp = 22;
02
03  if (temp >= 20)
04  {   String desc = "Hot";
05  }
06  else if (temp >= 10 && temp < 20 )
07  {   String desc = "Nice";
08  }

01  public void cold()
02  {   int temp = -27;
03  }
04
05  public void hot()
06  {   int temp = 27;
07  }

Variable not declared

This error occurs when a variable is not declared within the same (or an «outer») scope in which it is used. Recall that the scope of a variable declaration is determined by its location with { and } braces. The example below illustrates a simple case of this error. To fix this problem, make sure that the variable is declared either in the same scope in which it is being used, or it being delcared in an «outer» scope.

Example 1: Incorrect Code Example 1: Fixed Code

The variable balance is declared within the scope of the first if statement, so line 9 will cause an error.

To fix the problem, we declare balance in the scope of the entire method so that it can be referred to in all places within the method.

01  boolean newAcct = true;
02  double deposit = 17.29;
03    
04  if (newAcct == true)
05  {   double balance = 100.0;
06  }
07    
08  if (deposit > 0)
09  {   balance += deposit;
10  }
01  boolean newAcct = true;
02  double deposit = 17.29;
03  double balance = 0;

04    
05  if (newAcct == true)
06  {   balance = 100.0;
07  }
08    
09  if (deposit > 0)
10  {   balance += deposit;
11  }

Return to Main Page

Created by Terry Anderson (tanderso at uwaterloo dot ca) for use by ISG, Spring 2005

While working with the programming languages like executing a software program, there are many instances that we run into issues due to the run time errors or compilation errors. All these errors occur when the application is running. You might come across an instance where the application acts differently in a negative way to the requirements, then it means that a runtime error took place.

As it is one of the most common type of error that occurs during a software executive, let us get a deep idea on how to fix common types of runtime errors in Java and also the steps to be taken to resolve them on a timely basis.

Contents

  • 1 Fix the 5 Most Common Types of Runtime Errors in Java
    • 1.1  What is a Runtime Error in Java?
    • 1.2 Differences Between Compile Time Error and Runtime Error in Java
    • 1.3 Why Runtime Error Occurs in Java ?
    • 1.4 1. Accessing Out of Range Value in an Array
    • 1.5 2. Division by Zero Error
    • 1.6 3. Less Space or Insufficient Space Memory Error
    • 1.7 4. Conversion of an Invalid string into a Number
    • 1.8 5. Attempting to Store an Incompatible Value to a Collection
    • 1.9 How to solve Runtime Rrror in Java Programming?

Fix the 5 Most Common Types of Runtime Errors in Java

 What is a Runtime Error in Java?

A runtime error in Java is referred to as an application error that comes up during the execution process of the program. This runtime error usually takes place when the syntax is corrected as expected while the issue lies during the program execution. All these errors can be detected by JVM – Java Virtual Machine and cannot be identified during the compilation time. Java is one of the most sought-after programming languages for the hiring managers across the world. So become an expert in Java through our Java Training and grab the best job opportunity.

Now, In this post, Let us discuss the top runtime errors in Java.

  1. Division by zero errors
  2.  IO errors
  3. Out of range errors
  4. Undefined object errors

Differences Between Compile Time Error and Runtime Error in Java

Compile time errors are those errors in which the syntax would be incorrect in the application code. An example would be like missing semicolons, parenthesis, incorrect keywords, usage of undeclared variables, etc. 

The Java compiler is capable of detecting the syntax errors during the compile time and the error message will be appearing on the screen. The compiler is also capable of preventing the code from the execution unless and until the error is resolved. Therefore it is important that these errors are addressed by making the necessary changes before the program is successfully executed.

The runtime errors occur during the program execution after the compilation has completed. Any program that is throwing a runtime error means that there are no issues with Syntax in the program.

Why Runtime Error Occurs in Java ?

 Below listed are the most common types of runtime errors that occur in Java.

  1. Accessing an element that is out of range in an array
  2. Dividing a number with 0
  3. Less space or insufficient space memory
  4. Conversion of an invalid string into a number
  5. Attempting to store an incompatible value to a collection

When you come across such an address, you need to know that the Java compiler will be generating an error message and the program gets terminated abnormally. Runtime errors do not require to be caught explicitly. It is useful if you catch the runtime errors and resolve them to complete the program execution. 

Let us review a few of the most common runtime errors in Java programming with examples to gain a deeper understanding.

1. Accessing Out of Range Value in an Array

public class ValueOutOfRangeErrorExample {

public static void main(String[] args) {

     int k[] = new int[8];

        System.out.println(«8th element in array: « + k[8]);

}

}

In the above example, the array is initialized with 8 elements. with the above code, An element at position number 8 is trying to get access and does not exist at all, leading to the Exception java.lang.ArrayIndexOutOfBoundsException:

Error :

Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException:

Index 8 out of bounds for length 8  

at ValueOutOfRangeErrorExample.main(ValueOutOfRangeErrorExample.java:4)

2. Division by Zero Error

Below is an example of java.lang.ArithmeticException which occurs when the user is trying to code in such a way that they perform the division by zero.

public class ArithmeticExceptionExample {

public static void main(String[] args) {

       int num1 = 10, num2 = 0;

          System.out.println(«Result: «+ num1/num2);

}

}

In the above code, the integer num1 is getting to be divided by num2 which has a value of zero, which is leading to the exception called java.lang.ArithmeticException

Below is the Error Thrown :

Exception in thread «main» java.lang.ArithmeticException: / by zero

at ArithmeticExceptionExample.main(ArithmeticExceptionExample.java:4)

3. Less Space or Insufficient Space Memory Error

Below is an example of java.lang.OutOfMemoryError, which occurs when the user is trying to initialize an Integer array with a very large size, and due to the Java heap being insufficient to allocate this memory space, it throws an Error  java.lang.OutOfMemoryError: Java heap space

public class OutOfMemory {

public static void main(String[] args) {

Integer[] myArray = new Integer[1000*1000*1000];

}

}

Error :

Exception in thread «main» java.lang.OutOfMemoryError: Java heap space

at OutOfMemory.main(OutOfMemory.java:5)

4. Conversion of an Invalid string into a Number

Below is an example of java.lang.NumberFormatException, occurs when the user is trying to convert an alphanumeric string to an integer which leads to java.lang.NumberFormatException

public class NumberFormatException {

public static void main(String[] args) {

int a;

a= Integer.parseInt(«12Mehtab»);

System.out.println(a);

}

}

Error :

Exception in thread «main» java.lang.NumberFormatException: For input string: «12Mehtab»

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:580)

at java.lang.Integer.parseInt(Integer.java:615)

at NumberFormatException.main(NumberFormatException.java:6)

5. Attempting to Store an Incompatible Value to a Collection

Below is an example where user has created the ArrayList of String but trying to store the integer value which leads to Exception   java.lang.Error: Unresolved compilation problem

import java.util.ArrayList;

public class IncompatibleType {

public static void main(String[] args) {

ArrayList<String> student = new ArrayList<>();

student.add(1);

}

}

Error :

Exception in thread «main» java.lang.Error: Unresolved compilation problem:

The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int)

at IncompatibleType.main(IncompatibleType.java:7)

How to solve Runtime Rrror in Java Programming?

 The runtime errors can be solved by using the try catch blocks in Java. Below are the steps to be followed:

  1. You will need to Surround the statements that are capable of throwing an exception or a runtime error in the try catch blocks.
  2. The next step is to catch the error.
  3. Based on the requirements of the court or an application, it is important to take the necessary action.

Like we discussed earlier about the ArithmeticException example, it can be corrected by making the below changes.

public class ArithmeticExceptionExample {

public static void main(String[] args) {

     try {

         int num1 = 10, num2 = 0;

         System.out.println(«Result: « + num1/num2);

     } catch (ArithmeticException ae) {

         System.out.println(«Arithmetic Exception — cannot divide by 0»);

     }

        System.out.println(«Let’s continue the execution…»);

}

}

As the code is surrounded in the try catch blocks, the program will continue to execute after the exception is encountered.

Result :

Arithmetic Exception cannot divide by 0

Lets continue the execution...

In this way, it is important for you to identify the Runtime errors and also clear them without any hesitation. You can make use of the try catch blocks and many other resolutions which were helped in successful program execution. Also you will be able to track, manage and analyze the errors in real time. So this was all from this tutorial about fixing the 5 most common types of Runtime Errors in Java But still, if you have any queries, feel free to ask in the comment section. And don’t forget to stay tuned with the Tutorials field to learn this type of awesome tutorial. HAPPY CODING.

People Are Also Reading…

  • How to Play Mp3 File in Java Tutorial | Simple Steps
  • Menu Driven Program in Java Using Switch Case
  • Calculator Program in Java Swing/JFrame with Source Code
  • Registration Form in Java With Database Connectivity
  • How to Create Login Form in Java Swing
  • Text to Speech in Java
  • How to Create Splash Screen in Java
  • Java Button Click Event
  • 11 Best WebSites to Learn Java Online for Free

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the user. The errors are not detected till the compilation of a program is completed. A program without errors can only be successfully compiled and executed.

In the field of computer science, we are very familiar with compile-time and run-time errors. The time when the java file (source) is converted into the class file (executable) is called Compile time and the time when the class file (executable) starts executing or running is called run time. Different types of errors occur in both compile-time and run-time.

An error may occur sometimes due to incorrect syntax and sometimes even if the syntax is correct errors occur. The incorrect syntax cause errors in the program that kind of errors are known as compile-time errors because these errors are displayed at the time of compilation and other errors are run-time errors that are displayed at the time of running.

From the above statement, based on the time of occurrence of error the errors on classified into two types they are as shown below.

  1. Compile-time error.
  2. Run-time error.

Compile-time Error

The incorrect syntax cause errors in the program that kind of errors are known as compile-time errors. By the compiler at the time of compilation errors are thrown. Compile time errors are also mentioned as syntax errors.

Compile-time syntax:

Javac filename.java

The above syntax is used to compile the java file (source). If there are any syntax errors in a program then the compiler detects the error and displays them on the console. These kinds of errors are easily detected and pointed out by the compiler. The programmer easily finds and sorts out the error. The compiler specifies the error type and where it has occurred.

Types of Compile-time Errors

The compile time errors are occurred due to missing parenthesis, missing a semicolon, utilizing undeclared variables, etc.

There are 3 types of compile time errors they are as shown below:

1.Syntactical errors: Because syntax was incorrect, these types of errors occur. In the program. The below mentioned are some of the syntactical errors.

  • Error in structure
  • Missing operators
  • Unbalanced parenthesis

Program: This example program is without specifying condition in if statement.

class java18
{
public static void main(String args[])
{
int a=20;
                                            if()            // without condition
System.out.println("number is 20");
else
System.out.println("number is not 20");
}
}

Output:

java18.java:6: error: illegal start of expression

if()

^

1 error

  • Error in structure:    An error occurred, «=» is usedwhen «==» is needed.

Program:

class java18
{
public static void main(String args[])
{
int a=20;
  if(a=20)   // used “=” instead of “==”
System.out.println("number is 20");
else
System.out.println("number is not 20");
}
}

Output:

java18.java:6: error: incompatible types: int cannot be converted to boolean

if(a=20)

^

1 error

  • Missing operators:  An error occurred, when “; ” is missed.

Program:

class java18
{
public static void main(String args[])
{
int a=20     // missed “ ; “ (semicolon)
   if(a=20)   
System.out.println("number is 20");
else
System.out.println("number is not 20");
}
}

Output:

java18.java:5: error: ‘;’ expected

int a=20

^

1 error

  • Unbalanced parenthesis: error occurs when we miss the parenthesis and error in expression.

Program:

class java18
{
public static void main(String args[])
{
int a=20,b=10,c;
                                                      c=a+*b;                    // expression error 
                                           System.out.println("c="+c;     //missing parenthesis
}
}

Output:

java18.java:6: error: illegal start of expression

c=a+*b;

^

java18.java:7: error: ‘)’ expected

System.out.println(«c=»+c;

^

2 errors

2. Semantic errors: Due to the unclarity of code, these types of errors occurred. The below mentioned are some of the syntactical errors. The below mentioned are some of the semantic errors.

  • Incompatible types of operands
  • Undeclared variable
  • Incompatible types of operands: error occurred due to the incompatibility.

Program:

class java18
{
public static void main(String args[])
{
int a="hello";//the String type and int are not compatible
System.out.println(a);
}
}

Output:

java18.java:5: error: incompatible types: String cannot be converted to int

int a=»hello»;

^

1 error

  • Undeclared variable: error occurred due to the not initialization.

Program:

class java18
{
public static void main(String args[])
{
int a=10;
System.out.println(b);//undeclared variable
}
}

Output:

java18.java:6: error: cannot find symbol

System.out.println(b);

^

symbol:   variable b

location: class java18

1 error

3. Lexical Errors: In the code, the error occurred due to an invalid character involved. Example program with invalid variable.

Program:

class java18
{
public static void main(String args[])
{
int +a=10;  // invalid variable
System.out.println(a);
}
}

Output:

java18.java:5: error: not a statement

int +a=10;

^

java18.java:5: error: ‘;’ expected

int +a=10;

^

2 errors

Понравилась статья? Поделить с друзьями:
  • Compile python extensions error
  • Compile make driver error 127
  • Compile failed see the compiler error output for details
  • Compile error что такое
  • Compile error wrong number of arguments or invalid property assignment