There are many types of errors that could be encountered while developing Java software, but most are avoidable. We’ve rounded up 50 of the most common Java software errors, complete with code examples and tutorials to help you work around common coding problems.
For more tips and tricks for coding better Java programs, download our Comprehensive Java Developer’s Guide, which is jam-packed with everything you need to up your Java game – from tools to the best websites and blogs, YouTube channels, Twitter influencers, LinkedIn groups, podcasts, must-attend events, and more.
If you’re working with .NET, you should also check out our guide to the 50 most common .NET software errors and how to avoid them. But if your current challenges are Java-related, read on to learn about the most common issues and their workarounds.
Compiler error messages are created when the Java software code is run through the compiler. It is important to remember that a compiler may throw many error messages for one error. So fix the first error and recompile. That could solve many problems.
1. “… Expected”
This error occurs when something is missing from the code. Often this is created by a missing semicolon or closing parenthesis.
Often this error message does not pinpoint the exact location of the issue. To find it:
- Make sure all opening parenthesis have a corresponding closing parenthesis.
- Look in the line previous to the Java code line indicated. This Java software error doesn’t get noticed by the compiler until further in the code.
- Sometimes a character such as an opening parenthesis shouldn’t be in the Java code in the first place. So the developer didn’t place a closing parenthesis to balance the parentheses.
Check out an example of how a missed parenthesis can create an error (@StackOverflow).
2. “Unclosed String Literal”
The “unclosed string literal” error message is created when the string literal ends without quotation marks, and the message will appear on the same line as the error. (@DreamInCode) A literal is a source code of a value.
Commonly, this happens when:
- The string literal does not end with quote marks. This is easy to correct by closing the string literal with the needed quote mark.
- The string literal extends beyond a line. Long string literals can be broken into multiple literals and concatenated with a plus sign (“+”).
- Quote marks that are part of the string literal are not escaped with a backslash (“\”).
Read a discussion of the unclosed string literal Java software error message. (@Quora)
3. “Illegal Start of an Expression”
There are numerous reasons why an “illegal start of an expression” error occurs. It ends up being one of the less-helpful error messages. Some developers say it’s caused by bad code.
Usually, expressions are created to produce a new value or assign a value to a variable. The compiler expects to find an expression and cannot find it because the syntax does not match expectations. (@StackOverflow) It is in these statements that the error can be found.
Browse discussions of how to troubleshoot the “illegal start of an expression” error. (@StackOverflow)
4. “Cannot Find Symbol”
This is a very common issue because all identifiers in Java need to be declared before they are used. When the code is being compiled, the compiler does not understand what the identifier means.
There are many reasons you might receive the “cannot find symbol” message:
- The spelling of the identifier when declared may not be the same as when it is used in the code.
- The variable was never declared.
- The variable is not being used in the same scope it was declared.
- The class was not imported.
Read a thorough discussion of the “cannot find symbol” error and examples of code that create this issue. (@StackOverflow)
5. “Public Class XXX Should Be in File”
The “public class XXX should be in file” message occurs when the class XXX and the Java program filename do not match. The code will only be compiled when the class and Java file are the same. (@coderanch):
To fix this issue:
- Name the class and file the same.
- Make sure the case of both names is consistent.
See an example of the “Public class XXX should be in file” error. (@StackOverflow)
6. “Incompatible Types”
“Incompatible types” is an error in logic that occurs when an assignment statement tries to pair a variable with an expression of types. It often comes when the code tries to place a text string into an integer — or vice versa. This is not a Java syntax error. (@StackOverflow)
There really isn’t an easy fix when the compiler gives an “incompatible types” message:
- There are functions that can convert types.
- The developer may need change what the code is expected to do.
Check out an example of how trying to assign a string to an integer created the “incompatible types.”(@StackOverflow)
7. “Invalid Method Declaration; Return Type Required”
This Java software error message means the return type of a method was not explicitly stated in the method signature.
There are a few ways to trigger the “invalid method declaration; return type required” error:
- Forgetting to state the type
- If the method does not return a value then “void” needs to be stated as the type in the method signature.
- Constructor names do not need to state type. But if there is an error in the constructor name, then the compiler will treat the constructor as a method without a stated type.
Follow an example of how constructor naming triggered the “invalid method declaration; return type required” issue. (@StackOverflow)
8. “Method <X> in Class <Y> Cannot Be Applied to Given Types”
This Java software error message is one of the more helpful error messages. It explains how the method signature is calling the wrong parameters.
The method called is expecting certain arguments defined in the method’s declaration. Check the method declaration and call carefully to make sure they are compatible.
This discussion illustrates how a Java software error message identifies the incompatibility created by arguments in the method declaration and method call. (@StackOverflow)
9. “Missing Return Statement”
The “missing return statement” message occurs when a method does not have a return statement. Each method that returns a value (a non-void type) must have a statement that literally returns that value so it can be called outside the method.
There are a couple reasons why a compiler throws the “missing return statement” message:
- A return statement was simply omitted by mistake.
- The method did not return any value but type void was not declared in the method signature.
Check out an example of how to fix the “missing return statement” Java software error. (@StackOverflow)
10. “Possible Loss of Precision”
“Possible loss of precision” occurs when more information is assigned to a variable than it can hold. If this happens, pieces will be thrown out. If this is fine, then the code needs to explicitly declare the variable as a new type.
A “possible loss of precision” error commonly occurs when:
- Trying to assign a real number to a variable with an integer data type.
- Trying to assign a double to a variable with an integer data type.
This explanation of Primitive Data Types in Java shows how the data is characterized. (@Oracle)
11. “Reached End of File While Parsing”
This error message usually occurs in Java when the program is missing the closing curly brace (“}”). Sometimes it can be quickly fixed by placing it at the end of the code.
The above code results in the following error:
Coding utilities and proper code indenting can make it easier to find these unbalanced braces.
This example shows how missing braces can create the “reached end of file while parsing” error message. (@StackOverflow)
12. “Unreachable Statement”
“Unreachable statement” occurs when a statement is written in a place that prevents it from being executed. Usually, this is after a break or return statement.
Often simply moving the return statement will fix the error. Read the discussion of how to fix unreachable statement Java software error. (@StackOverflow)
13. “Variable <X> Might Not Have Been Initialized”
This occurs when a local variable declared within a method has not been initialized. It can occur when a variable without an initial value is part of an if statement.
Read this discussion of how to avoid triggering the “variable <X> might not have been initialized”error. (@reddit)
14. “Operator … Cannot be Applied to <X>”
This issue occurs when operators are used for types not in their definition.
This often happens when the Java code tries to use a type string in a calculation. To fix it, the string needs to be converted to an integer or float.
Read this example of how non-numeric types were causing a Java software error warning that an operator cannot be applied to a type. (@StackOverflow)
15. “Inconvertible Types”
The “inconvertible types” error occurs when the Java code tries to perform an illegal conversion.
For example, booleans cannot be converted to an integer.
Read this discussion about finding ways to convert inconvertible types in Java software. (@StackOverflow)
16. “Missing Return Value”
You’ll get the “missing return value” message when the return statement includes an incorrect type. For example, the following code:
Returns the following error:
Usually, there is a return statement that doesn’t return anything.
Read this discussion about how to avoid the “missing return value” Java software error message. (@coderanch)
17. “Cannot Return a Value From Method Whose Result Type Is Void”
This Java error occurs when a void method tries to return any value, such as in the following example:
Often this is fixed by changing to method signature to match the type in the return statement. In this case, instances of void can be changed to int:
Read this discussion about how to fix the “cannot return a value from method whose result type is void” error. (@StackOverflow)
18. “Non-Static Variable … Cannot Be Referenced From a Static Context”
This error occurs when the compiler tries to access non-static variables from a static method(@javinpaul):
To fix the “non-static variable … cannot be referenced from a static context” error, two things can be done:
- The variable can be declared static in the signature.
- The code can create an instance of a non-static object in the static method.
Read this tutorial that explains what is the difference between static and non-static variables. (@sitesbay)
19. “Non-Static Method … Cannot Be Referenced From a Static Context”
This issue occurs when the Java code tries to call a non-static method in a non-static class. For example, the following code:
Would return this error:
To call a non-static method from a static method is to declare an instance of the class calling the non-static method.
Read this explanation of what is the difference between non-static methods and static methods.
20. “(array) <X> Not Initialized”
You’ll get the “(array) <X> not initialized” message when an array has been declared but not initialized. Arrays are fixed in length so each array needs to be initialized with the desired length.
The following code is acceptable:
Read this discussion of how to initialize arrays in Java software. (@StackOverflow)
This is a runtime error message that occurs when the code attempts to access an array index that is not within the values. The following code would trigger this exception:
Here’s another example (@DukeU):
Array indexes start at zero and end at one less than the length of the array. Often it is fixed by using “<” instead of “<=” when defining the limits of the array index.
Check out this example of how an index triggered the “ArrayIndexOutOfBoundsException” Java software error message. (@StackOverflow)
This is an issue that occurs when the code attempts to access part of the string that is not within the bounds of the string. Usually, this happens when the code tries to create a substring of a string that is not as long as the parameters are set at. Here’s an example (@javacodegeeks):
Like array indexes, string indexes start at zero. When indexing a string, the last character is at one less than the length of the string. The “StringIndexOutOfBoundsException” Java software error message usually means the index is trying to access characters that aren’t there.
Here’s an example that illustrates how the “StringIndexOutOfBoundsException” can occur and be fixed. (@StackOverflow)
A “NullPointerException” will occur when the program tries to use an object reference that does not have a value assigned to it (@geeksforgeeks).
The Java program raises an exception often when:
- A statement references an object with a null value.
- Trying to access a class that is defined but isn’t assigned a reference.
Here’s discussion of when developers may encounter the “NullPointerException” and how to handle it. (@StackOverflow)
The “NoClassDefFoundError” will occur when the interpreter cannot find the file containing a class with the main method. Here’s an example from DZone (@DZone):
If you compile this program:
Two .class files are generated: A.class and B.class. Removing the A.class file and running the B.class file, you’ll get the NoClassDefFoundError:
This can happen if:
- The file is not in the right directory.
- The name of the class must be the same as the name of the file (without the file extension). The names are case sensitive.
Read this discussion of why “NoClassDefFoundError” occurs when running Java software. (@StackOverflow)
This error message will occur when the Java software tries to call a method of a class and the method no longer has a definition (@myUND):
Often the “NoSuchMethodFoundError” Java software error occurs when there is a typo in the declaration.
Read this tutorial to learn how to avoid the error message NoSuchMethodFoundError.” (@javacodegeeks)
“NoSuchProviderException” occurs when a security provider is requested that is not available (@alvinalexander):
When trying to find why “NoSuchProviderException” occurs, check:
- The JRE configuration.
- The Java home is set in the configuration.
- Which Java environment is used.
- The security provider entry.
Read this discussion of what causes “NoSuchProviderException” when Java software is run. (@StackOverflow)
AccessControlException indicates that requested access to system resources such as a file system or network is denied, as in this example from JBossDeveloper (@jbossdeveloper):
Read this discussion of a workaround used to get past an “AccessControlException” error. (@github)
An “ArrayStoreException” occurs when the rules of casting elements in Java arrays are broken. Arrays are very careful about what can go into them. (@Roedyg) For instance, this example from JavaScan.com illustrates that this program (@java_scan):
Results in the following output:
When an array is initialized, the sorts of objects allowed into the array need to be declared. Then each array element needs be of the same type of object.
Read this discussion of how to solve for the “ArrayStoreException.” (@StackOverflow)
29. “Bad Magic Number”
This Java software error message means something may be wrong with the class definition files on the network. Here’s an example from The Server Side (@TSS_dotcom):
The “bad magic number” error message could happen when:
- The first four bytes of a class file is not the hexadecimal number CAFEBABE.
- The class file was uploaded as in ASCII mode not binary mode.
- The Java program is run before it is compiled.
Read this discussion of how to find the reason for a “bad magic number.” (@coderanch)
30. “Broken Pipe”
This error message refers to the data stream from a file or network socket has stopped working or is closed from the other end (@ExpertsExchange).
The causes of a broken pipe often include:
- Running out of disk scratch space.
- RAM may be clogged.
- The datastream may be corrupt.
- The process reading the pipe might have been closed.
Read this discussion of what is the Java error “broken pipe.” (@StackOverflow)
31. “Could Not Create Java Virtual Machine”
This Java error message usually occurs when the code tries to invoke Java with the wrong arguments (@ghacksnews):
It often is caused by a mistake in the declaration in the code or allocating the proper amount of memory to it.
Read this discussion of how to fix the Java software error “Could not create Java Virtual Machine.” (@StackOverflow)
32. “class file contains wrong class”
The “class file contains wrong class” issue occurs when the Java code tries to find the class file in the wrong directory, resulting in an error message similar to the following:
To fix this error, these tips could help:
- Make sure the name of the source file and the name of the class match — including case.
- Check if the package statement is correct or missing.
- Make sure the source file is in the right directory.
Read this discussion of how to fix a “class file contains wrong class” error. (@StackOverflow)
The “ClassCastException” message indicates the Java code is trying to cast an object to the wrong class. In this example from Java Concept of the Day, running the following program:
Results in this error:
The Java code will create a hierarchy of classes and subclasses. To avoid the “ClassCastException” error, make sure the new type belongs to the right class or one of its parent classes. If Generics are used, these errors can be caught when the code is compiled.
Read this tutorial on how to fix “ClassCastException” Java software errors. (@java_concept)
The “ClassFormatError” message indicates a linkage error and occurs when a class file cannot be read or interpreted as a class file.
There are several reasons why a “ClassFormatError” can occur:
- The class file was uploaded as in ASCII mode not binary mode.
- The web server must send class files as binary not ASCII.
- There could be a classpath error that prevents the code from finding the class file.
- If the class is loaded twice, the second time will cause the exception to be thrown.
- An old version of Java runtime is being used.
Read this discussion about what causes the “ClassFormatError” in Java. (@StackOverflow)
“ClassNotFoundException” only occurs at run time — meaning a class that was there during compilation is missing at run time. This is a linkage error.
Much like the “NoClassDefFoundError,” this issue can occur if:
- The file is not in the right directory.
- The name of the class must be the same as the name of the file (without the file extension). The names are case sensitive.
Read this discussion of what causes “ClassNotFoundException” the for more cases. (@StackOverflow).
This Java issue will occur when something goes wrong with a static initialization (@GitHub). When the Java code later uses the class, the “NoClassDefFoundError” error will occur.
There needs to be more information to fix the error. Using getCause() in the code can return the exception that caused the error to be returned.
Read this discussion about how to track down the cause of the ExceptionInInitializerError. (@StackOverflow)
An “IllegalBlockSizeException” will occur during decryption when the length message is not a multiple of 8 bytes. Here’s an example from ProgramCreek.com (@ProgramCreek):
The “IllegalBlockSizeException” could be caused by:
- Different encryption and decryption algorithm options used.
- The message to be decrypted could be truncated or garbled in transmission.
Read this discussion about how to prevent the IllegalBlockSizeException Java software error message. (@StackOverflow)
A “BadPaddingException” will occur during decryption when padding was used to create a message than can be measured by a multiple of 8 bytes. Here’s an example from Stack Overflow (@StackOverflow):
Encrypted data is binary so don’t try to store it in a string or the data was not padded properly during encryption.
Read this discussion about how to prevent the BadPaddingException. (@StackOverflow)
An “IncompatibleClassChangeError” is a form of LinkageError that can occur when a base class changes after the compilation of a child class. This example is from How to Do in Java (@HowToDoInJava):
When the “IncompatibleClassChangeError” occurs, it is possible that:
- The static on the main method was forgotten.
- A legal class was used illegally.
- A class was changed and there are references to it from an another class by its old signatures. Try deleting all class files and recompiling everything.
Try these steps to resolve the “IncompatibleClassChangeError.” (@javacodegeeks)
This Java software error message is thrown when a file with the specified pathname does not exist.
In addition to files not existing the specified pathname, this could mean the existing file is inaccessible.
Read this discussion about why the “FileNotFoundException” could be thrown. (@StackOverflow)
An “EOFException” is thrown when an end of file or end of stream has been reached unexpectedly during input. Here’s an example from JavaBeat of an application that throws an EOFException:
Running the program above results in the following exception:
When there is no more data while the class DataInputStream is trying to read data in the stream, “EOFException” will be thrown. It can also occur in the ObjectInputStream and RandomAccessFile classes.
Read this discussion about when the “EOFException” can occur while running Java software. (@StackOverflow)
This Java software error message is thrown when character encoding is not supported (@Penn).
It is possible that the Java Virtual Machine being used doesn’t support a given character set.
Read this discussion of how to handle “UnsupportedEncodingException” while running Java software. (@StackOverflow)
A “SocketException” indicates there is an error creating or accessing a socket (@ProgramCreek).
This exception usually is thrown when the maximum connections are reached due to:
- No more network ports available to the application.
- The system doesn’t have enough memory to support new connections.
Read this discussion of how to resolve “SocketException” issues while running Java software. (@StackOverflow)
This Java software error message occurs when there is failure in SSL-related operations. The following example is from Atlassian (@Atlassian):
This can happen if:
- Certificates on the server or client have expired.
- Server port has been reset to another port.
Read this discussion of what can cause the “SSLException” error in Java software. (@StackOverflow)
A “MissingResourceException” occurs when a resource is missing. If the resource is in the correct classpath, this is usually because a properties file is not configured properly. Here’s an example (@TIBCO):
Read this discussion of how to fix “MissingResourceException” while running Java software.
A “NoInitialContextException” occurs when the Java application wants to perform a naming operation but can’t create a connection (@TheASF).
This can be a complex problem to solve but here are some possible problems that cause the “NoInitialContextException” Java error message:
- The application may not have the proper credentials to make a connection.
- The code may not identify the implementation of JNDI needed.
- The InitialContext class may not be configured with the right properties.
Read this discussion of what “NoInitialContextException” means when running Java software. (@StackOverflow)
A “NoSuchElementException” happens when an iteration (such as a “for” loop) tries to access the next element when there is none.
The “NoSuchElementException” can be thrown by these methods:
Read this tutorial of how to fix “NoSuchElementException” in Java software. (@javinpaul)
This Java software error message is thrown when an application tries to access a field in an object but the specified field no longer exists in the onbject (@sourceforge).
Usually, this error is caught in the compiler but will be caught during runtime if a class definition has been changed between compile and running.
Read this discussion of how to find what causes the “NoSuchFieldError” when running Java software. @StackOverflow
This Java software error message occurs when the application tries to convert a string to a numeric type, but that the number is not a valid string of digits (@alvinalexander).
The can “NumberFormatException” be thrown when:
- Leading or trailing spaces in the number.
- The sign is not ahead of the number.
- The number has commas.
- Localisation may not categorize it as a valid number.
- The number is too big to fit in the numeric type.
Read this discussion of how to avoid “NumberFormatException” when running Java software. (@StackOverflow).
This Java software error message occurs when a blocking operation times out.
Read this discussion about how to handle “TimeoutException” when running Java software. (@StackOverflow).
And that wraps it up! If you’ve followed along the whole way, you should be ready to handle a variety of runtime and compiler errors and exceptions. Feel free to keep both of these articles saved or otherwise bookmarked for quick recall. And for the ultimate Java developer’s toolkit, don’t forget to download The Comprehensive Java Developer’s Guide.