Java error messages
Error messages in the console when compiling and running code are not always self-explanatory. To give you a better overview of what the errors mean and how to fix them, the most common errors are listed here.
Depending on the Java version you are using, messages may appear in English or German.
What should I do if I still cannot figure it out?
Look up the error message:
You can also use the browser built into 5Code for
this.
Ask your tutors:
If no solution can be found and fellow students cannot help
either, the tutors are always happy to assist.
Compile errors
Array required, but <X> found
array required but String found String b = a[0]; ^
Possible causes
-
Accessing an index with
[]on a variable that is not an array type
Possible solutions
- Check the type of the variable
- Use the appropriate access method for the type, e.g. "get()" for lists
ERROR_array_required
Cannot find symbol
cannot find symbol positionX = x; ^symbol: variable positionXlocation: class Block
Possible causes
- Variable was not defined
- Name is misspelled
- Missing "new" when creating an object
Possible solutions
- Make sure the variable being used has been defined
- the first occurrence of a variable must include a data type
- Check for spelling mistakes in the name
Note:
The search feature can help you find a variable and its usage more quickly.
ERROR_cannot_find_symbol
class, interface, enum, or record expected
class, interface, enum, or record expected } ^
Possible causes
- Too many closing curly braces (})
Possible solutions
- Remove the extra braces
Note:
The extra braces are usually found at the end of the code for this error. Proper code indentation can help you find and avoid this error.
ERROR_class_expected
class, interface, annotation type, enum, record, method or field expected
class, interface, annotation type, enum, record, method or field expected
publi void begruessung(String name) {
^
Possible causes
- Invalid modifier (
static,public, ...)
Possible solutions
- Fix or remove the modifier
ERROR_class_interface_expected
Invalid method declaration; return type required
invalid method declaration; return type required
begruessung(String name) {
^
Possible causes
-
Missing return type (
void,int,boolean...)
Possible solutions
- Add the return type
ERROR_invalid_method_declaration
abcClass <X> is public, should be declared in a file named <X>.java
class Block is public, should be declared in a file named Block.javapublic class Block {
^
Possible causes
- The class name does not match the file name
Possible solutions
- Make the names match
Note:
When renaming a class, the corresponding file must also be renamed. 5Code automatically renames the class when you rename the file.
ERROR_class_file_name
Duplicate case label
duplicate case label case 's': ausgabe = "Daten werden gespeichert"; ^
Possible causes
- A case in a switch statement is used more than once.
Possible solutions
- Remove the duplicate case or change the literal to an unused value
Note:
When copying and pasting code from another location, make sure to adjust the code at all relevant places. (Ideally, avoid copy & paste!)
ERROR_duplicate_case_label
"else" without "if"
'else' without 'if' else { ^
Possible causes
- An else branch was found that cannot be assigned to any if statement ("dangling else").
Possible solutions
- Check your braces: wrap multiple statements under if in a block ({})
- Remove empty statements (;) after if
ERROR_else_without_if
Illegal start of expression/type
illegal start of expression void dreheAufWinkel(int winkel) { ^illegal start of type return str; ^
Possible causes
- Missing braces
- A method is placed inside another method
- A statement is placed outside a method
- Access modifiers (public, protected, private) used inside a method
Possible solutions
- Check your braces
Note:
Proper code indentation can help you find and avoid this error. The cause of the error is very likely found in the lines before the error.
ERROR_illegal_start
Incompatible types
incompatible types: String cannot be converted to int int a = "a"; ^incompatible types: possible lossy conversion from double to int int x = Math.pow(2,4); ^
Possible causes
- A variable is assigned a value of the wrong type
Possible solutions
- Check whether the variable was confused with another one
- Convert the value (if possible)
Note:
Floating-point numbers can also be converted to integers, e.g. int pi = (int)3.14159. Note that the values will be rounded. Strings consisting of numbers can also be converted, e.g. Integer.parseInt("500").
ERROR_incompatible_types
Invalid method declaration; return type required
invalid method declaration; return type required public toString() { ^
Possible causes
- Missing return type in the method declaration
Possible solutions
- Add the appropriate return type (void, int, String, ...)
Note:
Even if the method does not return a value, it must be explicitly declared as "void".
ERROR_return_type
Method <X> is already defined in class <Y>
method toString() is already defined in class Block public String toString() { ^
Possible causes
- A method with this name and the given parameters has already been declared in the class
Possible solutions
- Change the method name
- Change the types or number of parameters
ERROR_method_already_defined
Method <X> in class <Y> cannot be applied to given types
method positioniereAuf in class Block cannot be applied to given types; block.positioniereAuf(2); ^required: int,intfound: intreason: actual and formal argument lists differ in length
Possible causes
- The parameters of the called method do not match its definition
Possible solutions
- Adjust the parameters to match the definition (number and type)
Note:
The error message details which parameters are expected and which were provided. The search feature can help you find the method definition more quickly.
ERROR_cannot_be_applied_to_types
Missing return statement
missing return statement } ^
Possible causes
- A method with a return type (not "void") does not return a value
- "return" is not called in every case (e.g. inside an if branch)
Possible solutions
- Add "return" with the appropriate return value at the end of the method
- Check that all branches call "return"
Note:
If different values are returned under certain conditions (if), the other conditions must be introduced with "else if". Otherwise the compiler cannot guarantee that a value is returned in every case.
ERROR_missing_return
Non-static variable <X> cannot be referenced from a static context
non-static variable name cannot be referenced from a static context name = "Alice"; ^
Possible causes
- An instance property of the class is being accessed from within a static method.
Possible solutions
- Define the variable as static
- Create an instance of the class and access it through the instance
ERROR_non_static_variable
Not a statement
not a statement abc ^
Possible causes
- There is no valid statement present
Possible solutions
- For method calls: add ()
- For variables: add an assignment (e.g. = otherVariable)
- Make sure comments are properly marked as comments
ERROR_not_a_statement
Package <X> does not exist
package aufgaben does not exist import aufgaben.*; ^package system does not exist system.out.println("Hello world"); ^
Possible causes
- Package name or path was specified incorrectly
- A class name was written in lowercase, e.g. when calling "System.out.println()"
Possible solutions
- Check the name and location of the imported package
- Fix lowercase class names
ERROR_package_does_not_exist
Reached end of file while parsing
reached end of file while parsing } ^
Possible causes
- Not all braces are properly closed
Possible solutions
- Add the missing braces
Note:
Proper code indentation can help you find and avoid this error.
ERROR_end_of_file
Unclosed character literal
unclosed character literal char zeichen = 'a; ^
Possible causes
- A char literal is not properly closed
- A char literal contains more than one character
Possible solutions
- Add the closing ' to the char literal
- For multiple characters, use the String data type
ERROR_unclosed_character_literal
Unreachable statement
unreachable statement System.out.println(str); ^
Possible causes
- Code lines after a "return" or "break" (within the same block)
Possible solutions
- Move the code lines before "return" or "break"
ERROR_unreachable_statement
uses unchecked or unsafe operations
Note: [...]\Super.java uses unchecked or unsafe operations.
What causes this warning?
- Using raw types with generics
How can I fix this warning?
- Assign a type parameter when using generics
ERROR_unsafe_operations
Variable <X> might not have been initialized
variable str might not have been initialized System.out.println(str);
^
Possible causes
- Variable was not initialized
- Variable is only initialized under certain conditions
Possible solutions
- Initialize the variable before using it
- Check that all branches initialize the variable
Note:
If variables are initialized under certain conditions (if), the other conditions must be introduced with "else if". Otherwise the compiler cannot guarantee that the variable is initialized in every case.
ERROR_var_not_initialized
Variable <X> is already defined in method <Y>
variable a is already defined in method main(String[]) int a = 9; ^
Possible causes
- A variable with this name has already been declared in the block
Possible solutions
- Change the variable name
- Check the scopes of the blocks
Note:
Within a block, duplicate variable names are not allowed, even if they have different types.
ERROR_var_already_defined
<identifier> expected
<identifier> expected System.out.println("Hello world");
^
Possible causes
- Incorrect braces
- Statements are placed outside a method
Possible solutions
- Check your braces
- Move statements into a method (e.g. main())
Note:
Proper code indentation can help you find and avoid this error.
ERROR_identifier_expected
<X> expected
';' expected
position X = 0 ^
Possible causes
- Missing character (e.g. ";" or "{")
- Incorrect braces
Possible solutions
- Add the missing character at the indicated position
- Check your braces
ERROR_expected
<X> has private access in <Y>
name has private access in Person String name = person.name;
^
Possible causes
- Accessing instance variables or methods that have private visibility
Possible solutions
- For instance methods: change the visibility as needed (public, protected, default)
- For instance variables: these should remain private, and direct access to instance variables from outside must be avoided. Try to adjust your logic so that direct access is not needed.
ERROR_private_access
<X> in <Y> has been deprecated
[deprecation] stop() in Thread has been deprecated t.stop(); ^[removal] Integer(int) in Integer has been deprecated and marked for
removal Integer i = new Integer(5);
^
What causes this warning?
- Methods or constructors have been used that are no longer intended for use. These are marked as "deprecated" in the API documentation. Over the course of Java's development, some methods or constructors have been revised or replaced with better, safer versions or alternative methods.
How can I fix this warning?
- Check the API documentation for the better, safer version you should use instead. There may also be hints in the assignment instructions.
ERROR_deprecation
Bad operand type <X> for unary operator "<Y>"
bad operand type boolean for unary operator '++' bool++; ^
Possible causes
- An operator is being applied to an incompatible data type.
Possible solutions
- Check whether the operator is being applied to the correct variable.
- Check whether the variable has a compatible type.
-
+,-,/,*,%can be applied to two numeric types, e.g.3 + 5 !can be applied to boolean, e.g.!isTooFast-
++and--can be applied to numeric types, e.g.i-- -
&,&&,|,||can be applied to boolean, e.g.isBig && isFast
ERROR_bad_operand
Incomparable types: <X> and <Y>
incomparable types: boolean and int boolean bool3 = bool == 8;
^
Possible causes
- An attempt is made to compare values of two types that cannot be compared, e.g. boolean and int.
- Booleans can be compared with each other, and numeric values can be compared with each other. Mixing them is not possible.
Possible solutions
- Check whether the correct values or variables are being compared.
- Check whether the elements being compared have the correct type.
ERROR_incomparable_types
Unnamed classes are a preview feature and are disabled by default.
unnamed classes are a preview feature and are disabled by default. void hello() { ^
Possible causes
- A definition is found outside the class where it does not belong.
Possible solutions
- Check whether the block above was closed only once (
}). - Check whether a method was closed incorrectly.
ERROR_unnamed_classes
Duplicate class: X
duplicate class: Testclass Test {^
Possible causes
- A class was named incorrectly.
Possible solutions
-
Check whether the class name and file name match (
ClassName.java), and adjust one of them accordingly. - Check whether the class name is used more than once in the project. This can happen if files are copied into the project from outside of 5Code.
ERROR_duplicate_class
Array dimension missing
array dimension missing int[] numbers = new int[];
^
Possible causes
- The size is missing when creating an array.
Possible solutions
- Add the array length inside the brackets, e.g.
new int[5].
ERROR_array_dimension_missing
'.class' expected
'.class' expected this.zahl = int _zahl;
^
Possible causes
- A data type is used incorrectly, e.g. when assigning a value.
Possible solutions
-
Make sure data types are used when defining a variable, not when assigning a
value (i.e. on the left side of
=). - Make sure data types are used when defining formal parameters, not in actual arguments.
ERROR_dot_class_expected
Compact source file does not have main method in the form of void main() or void main(String[] args)
void mains() {
^
Possible causes
- A main() method is missing, which is required to run the program.
Possible solutions
- Add a "void main()" if it is missing.
- Check for typos in the method name.
- This may not be the Java file that should be run. Try running a different file that has a "void main()".
ERROR_compact_source_file_main
Runtime errors
ArrayIndexOutOfBoundsException: <X>
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4
out of bounds for length 2
Possible causes
- Attempted access to a non-existent index in an array
Possible solutions
- Check the length of the array
- Check the index calculation
- Check the loop condition that accesses the array
Note:
Array indices go from 0 to array length - 1.
ERROR_array_oob
ClassCastException: <X>
Exception in thread "main" java.lang.ClassCastException: class
java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer
and java.lang.String are in module java.base of loader 'bootstrap')
Possible causes
- Casting an object of one class to an object of another class fails because the types are incompatible
Possible solutions
- Check the return type of the methods being used (do they return what is expected)
- Look up which types are compatible with each other
- Check the inheritance structure of the relevant classes
- Avoid untyped collections (raw types)
ERROR_class_cast
NullPointerException
Exception in thread "main" java.lang.NullPointerException
Possible causes
-
Attempted access to an element without a value (null), e.g.
- Accessing an array element whose value is null
- Querying the length of an array whose value is null
- Calling methods on a variable with the value null
Possible solutions
- Make sure the referenced values or variables are set
- Check if the variable is not null before performing operations
ERROR_null_pointer
StringIndexOutOfBoundsException: <X>
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: -1Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0,
end 4, length 1
Possible causes
- Attempted access to a non-existent index in a string
Possible solutions
- Check the length of the string
- Check the index calculation
- Check the loop condition that accesses the string
Note:
String indices go from 0 to string length - 1.
ERROR_string_oob
by zero
Exception in thread "main" java.lang.ExceptionInInitializerError Caused by:
java.lang.ArithmeticException: / by zero
Possible causes
- Mathematical operation: division by 0
Possible solutions
- Check the values of the variables involved in the division
- Wrap the calculation in a try/catch block
ERROR_divide_by_zero