User Tools

Site Tools


java_errors

Java Errors

This page is dedicated to presenting java errors and ways to go about finding the solution to the error. There are two sections, Compile-time and Runtime.

Compile-time errors are those that show up when trying to compile the class file.
Runtime errors are exceptions thrown while executing the program.

Compile-time errors start with the name of the class file, followed by the line where the error occurred, followed by the type of error, and finally the code where the error occurred.

  • Example:
    •       wiki.java:15: error: ')' expected
                if (i > j
                         ^

Runtime errors start with the word “Exception” followed by what method the error occurred in, followed by what the exception is and then what line the error occurred in the code.

  • Example:
    •       Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
            at wiki.main(wiki.java:17)
    • The “2” after the exception says what array index is the problem. The “17” is the code line.


An organized document of the Java errors listed here can be found at http://introcs.cs.princeton.edu/java/11cheatsheet/errors.pdf


Note: Many times multiple errors are the result from the errors preceding it. It is always good practice to fix errors one at a time, starting with the first error, and recompiling the program each time to see if the rest of the errors are resolved.

  • Example:
    • The following code is missing a closing bracket for the first method x().
      •         class NewClass {
                  void x() {
                    int n = 5;
         
                  void y() {
                    int m = 3;
                  }
                }
    • Three errors will occur when trying to compile this class:
      •           NewClass.java:5: illegal start of expression
                    void y() {
                    ^
                  NewClass.java:8: ';' expected
                  }
                  ^
                  NewClass.java:9: '}' expected
                  ^
    • The first error tells us that the code is missing something before the function y() is called. The function x() is missing a closing bracket. Adding a closing bracket will resolve the second and third error.

Compile-time Errors


... expected

Java is expecting a closing statement at the indicated line. Most of the time it is looking for a semicolon(;) or brackets [ ( ) { } ] but it could be something else based on the code line.

The code below…

if (i > j     // Missing right parenthesis
  max = i     // Missing semicolon
else
  max = j;

… Results in the following error

wiki.java:1: error: ')' expected
  if (i > j
           ^
wiki.java:2: error: ';' expected
  max = i
         ^
2 errors           

From the two errors we know line 1 is missing an expected right parenthesis and line 2 is missing an expected semicolon. Add these missing characters and the errors should be resolved.

unclosed string literal

Java is expecting the string to be closed with a quotation mark.

The code below…

String test = "this is not correct;

… Results in

wiki.java:1: error: unclosed string literal
     String test = "this is not correct;
                   ^

For instances where you want to continue a string on a new line (to make the code easier to read), a + sign will be needed to concatenate the two lines.

Incorrect:

String test = "I am trying to make my code
     look nice";

Correct:

String test = "I am trying to make my code" +
     "look nice";

illegal start of expression

Java is expecting an expression and cannot find one.

The below code…

if (x > y) )     // Extra parenthesis
     z = x;
else
     z = ;       // Missing right side of assignment

… Results in

wiki.java:1: error: illegal start of expression
     if (x > y) )
                ^
wiki.java:4: error illegal start of expression
     z = ;
         ^          

Remove the extra parenthesis and complete the assignment statement to resolve the errors.

not a statement

Java sees a syntactically correct statement but it is not used properly.

The below code…

max ;          // Assignment statement unfinished
 
if (x > y)
     max = x;
els ;          // Else not spelled correcty     

… Results in

wiki.java:1: error: not a statement
     max ;
     ^
wiki.java:5: error: not a statement
     els ;
     ^     

Finish the assignment statement and spell else correctly or remove it to resolve the errors.

cannot find symbol

This error occurs when trying to use an identifier outside its scope. Common instances of this are misspelling a variable or using a variable from a loop or function/method outside the loop/function/method.

The error will typically add a “symbol” and “location” which tells you which variable is causing the problem and what class it is located in.

The below code…

int[] a = {1, 2, 3};
int sum = 0;
 
for (int i = 0; i < a.length; i++)
     sum = sam + a[i];                 //"sam" should be "sum"
 
System.out.println("Last = " + i);     //'i' is only available within the for loop

… Results in

wiki.java:5: error: cannot find symbol
     sum = sam + a[i];
           ^
  symbol: variable sam
  location: class wiki
             
wiki.java:7: error: cannot find symbol
     System.out.println("Last = " + i);
                                    ^           
  symbol: variable i
  location: class wiki                                    

To resolve the errors, fix the spelling of “sam” to “sum” and make the variable 'i' outside the for loop, or create a variable outside the for loop and assign it to the value of 'i' within the for loop.

... is already defined in...

Identifiers can only be declared once in within the same scope.

The below code…

int x;
int x = 5;     // variable 'x' is already declared!

… Results in

wiki.java:2: error: variable x is already defined in method main(String[])
     int x = 5;
         ^

The program errored because the variable x was already declared in the main method. If the first x was declared inside a loop or other method before the second x then this would be acceptable.

array required but... found

Java is trying to assign a value to an array index to a variable that is not an array.

The below code…

int z;
z[2] = 4;     // z is not an array!

… Results in

wiki.java:2: error: array required, but int found
     z[2] = 4;

Make the variable z an integer array instead of an integer to assign an index. Or, delete the index assignment statement.

... has private access in ...

Variables declared as private in one class cannot be accessed from another class.

Make the variable public, or create a public method in the class that returns the private variable to the other class that called it.

variable... might not have been initialized

Variables created locally, non-global, do not have initial values. Attempting to use them without giving a default value will result in this error.

The below code…

int x = 1;      // default value set
int y;          // not initialized
int sum;
 
sum = x + y;

… Results in

wiki.java:5: error: variable y might not have been initialized
     sum = x + y;
               ^

Set a default value to y or set y equal to something before using the sum assignment statement to resolve the error.

... in ... cannot be applied to ...

This error results when a method call uses an incompatible type compared to the method's declaration type.

The below code…

public static void main(String[] args) {
 
  int y = m(5.6);     // Method m requires an int not a double!
 
}
 
void m(int i) {
 
  return i + 2;
 
}

… Results in

wiki.java:2: error: method m in class wiki cannot be applied to given types;
      m(5.4);
      ^
  required: int
  found: double
  reason: actual argument double cannot be converted to int by method invocation conversion      

To resolve the error either change the double value in the m() call to an integer, or change the parameter 'i' in m() to a double type.

bad operand types for... operator '...'

Certain operators cannot be performed on certain types. For example, a boolean cannot be added to an integer.

The below code…

int x = 5;
int max;
boolean status = true;
 
max = x + status;          //int cannot be added to boolean!

… Results in

wiki.java:5: error: bad operand types for binary operator '+'
     max = x + status;
             ^
  first type: int
  second type: boolean             

To resolve the error do not attempt to use operations on incompatible types such as boolean and int.

possible loss of precision

This error occurs when assigning a variable a type higher than its declaration. For example, declaring a variable as integer but assigning it a double. Declaring a variable as double and assigning it an integer is acceptable however.

The below code…

int x, y, max;
 
x = 5.5;         // Variable x is an int not a double!
y = 2;
 
max = x + y;     // This would make max a double but it is declared an int!

… Results in

wiki.java:3: error: possible loss of precision
     x = 5.5;
         ^
  required: int
  found: double
  
wiki.java:6: error: possible loss of precision
     max = x + y;
             ^
  required: int
  found: double                     

To resolve the error, change the value assigned to 'x' to be an integer, or declare variables 'x' and 'max' as doubles.

incompatible types

This error occurs when trying to assign a variable a value of an incompatible type. For example, assigning a boolean type to an int. Certain instances of this are acceptable however, such as assigning an integer to variable declared as a double.

The below code…

int x;
 
x = true;     // variable x is not a boolean!

… Results in

wiki.java:1: error: incompatible types
     x = true;
         ^
  required: int
  found: boolean         

To resolve the error, do not assign an incompatible type to a variable, or cast the assigned value as the variable being assigned's type (if allowed).

inconvertible types

Some conversions are not allowed. For example, it is not possible to convert a boolean type to an integer.

The below code…

int x;
 
x = (int)true;     // Cannot convert boolean to integer!

… Results in

wiki.java:3: error: inconvertible types
     x = (int)true;
              ^
  required: int
  found: boolean              

To resolve the error, do not attempt to convert one variable type to an inconvertable type.

missing return statement

Non-Void type methods MUST have a return statement for every path that leaves the method, even if that path is impossible to reach.

The below code…

public static void main(String[] args) {
  int x, y, max;
 
  x = 4;
  y = 5;
 
  max = m(x,y);
}
 
static int m(int i, int k) {
  if (i > k) return i;
  else if (i <=k) return k;     // What about when both these statements are false??
}

… Results in

wiki.java:14: error: missing return statement
  }
  ^

This particular error is not very descriptive. To resolve make sure that the method that produced the error has a return statement for all outcomes. Putting

Else return 0;

will help satisfy all outcomes.

missing return value

Non-Void methods must return the same value type as the method itself.

The below code…

public static void main(String[] args){
  int x, y, max;
 
  x = 4;
  y = 5;
 
  max = m(x,y);
}
 
static int m(int i, int k) {
  return;     // Must return an int value!
}

… Results in

wiki.java:11: error: missing return value
     return;
     ^

To resolve the error, make sure the return statement returns a data type that is the same as the method. In this case, putting an integer value after the return would suffice.

cannot return a value from method whose result type is void

Void methods cannot have a return statement which is an expression.

The below code…

public static void main(String[] args){
  int x, y, max;
 
  x = 4;
  y = 5;
 
  m(x, y);
}
 
static void m(int i, int k){
  return i + k;     // void methods cannot contain a returned expression!
}

… Results in

wiki.java:11: error: cannot return a value from method whose result type is void
     return i + k;
              ^

To resolve, remove the expression “i + k”.

invalid method declaration; return type required

All methods, except constructors, must have a return type or void specified.

The below code…

m(int i, int k) {     //method m must have a return type or be void!
  return i + k;
}

… Results in

wiki.java:1: error: invalid method declaration; return type required
     m(int i, intk) {
     ^

To resolve, declare a return type for the method or declare it as void.

unreachable statement

This error occurs when code is written after a return statement.

The below code…

static void m(int i, int k) {
  if (true) {
    return n + 1;
  }
  else {
    return n - 1;
    n = n + 1;     // This should be before the prior return statement!
    }
}

… Results in

wiki.java:7: error: unreachable statement
     k++;
     ^

To resolve, place the problem statement before the return statement, or remove the problem statement.

non-static method ... cannot be referenced from a static context

A non-static method cannot be called from a static method (such as main).

The below code…

public static void main(String[] args) {
  int x = 2;
 
  m(x);     // m is not static and cannot be called in a static method unless an object for the method is created.
}
 
void m(int k) {
  System.out.println("Value is " + k);
  return;
}

… Results in

wiki.java:4: error: non-static method m(int) cannot be referenced from a static context
     m(x);
     ^

To resolve the error, make the method static, or create an object variable for the method.



Runtime Errors


ArrayIndexOutOfRangeException

Exception thrown when trying to access an array index that does not exist.

The below code…

int a[] = new int[2];
 
a[1] = 5;
a[2] = 6;     // Index 2 does not exist! Array indexing starts at 0.

… Results in

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at wiki.main(wiki.java:4)

Resolving the error requires either the array to be resized, or take out the line that tries to access a bad index.

StringIndexOutOfBoundsException

Exception occurring when using a string method out of the bounds of the string.

The below code…

String test = "I hope I don't fail!";
 
System.out.println(test.charAt(20));     //String test does not have an index 20!

… Results in

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20
     at java.lang.String.charAt(Unknown Source)
     at wiki.main(wiki.java:3)

The error is caused by line 3 when calling the string method charAt(). String test does not have an index 20. Resolve the error by using a valid index.

NullPointerException

Exception occurring when trying to access or assign a null reference.

The below code…

Node node = getNextNode();
 
if (node.key > this.key) {     // What if node is null??
  ...
}
 
if (node != null) {           // This is the proper way
  if (node.key > this.key) {
    ...
  }
}

… Results in

Exception in thread "main" java.lang.NullPointerException at x.y(x.java:3)

Resolving the error requires fixing the code that is trying to use a Null pointer. It is best to start at the line where the error originated and check the code there.

InputMismatchException

Exception occurring when trying to use incompatible types while using the Scanner. For example, trying to scan a string value into an integer scan.

The below code…

Scanner s = new Scanner(System.in);
 
int a = s.nextInt();     // Expecting an integer from the scanner

After executing the program, the user types a string value instead of an integer…

… Results in

Exception in thread "main" java.util.InputMismatchException
     at ...
     at wiki.main(wiki.java:3)

To resolve the error, do not try to use incompatible types for the scanner desired.

ArithmeticException

Exception occurring when trying to divide by zero.

The below code…

int answer = 5 / 0;     // Dividing by zero is not allowed!

… Results in

Exception in thread "main" java.lang.ArithmeticException: / by zero
     at wiki.main(wiki.java:1)

To resolve the error, do not divide by zero.

outOfMemoryError

Exception thrown when the program has used up the memory allocated to it.

StackOverFlowArea

Exception thrown when the stack space has been used up. Recursion methods can cause this.

The below code…

public class wiki {
  
  public static void main(String[] args) {
    
    int answer = factorial(5);
    
    System.out.println(answer);
  }
  
  public static int factorial(int k) {
  
    if (k == 0) return 1;
    else return k * factorial(k+1);     // This will never finish!
  }
}

… Results in a very long list of exception line errors since it is trying to trace back to the start of the exception. You will most likely not even see the actual exception part of the error.

To resolve, go to the last visible line in the exception and get the code line from there. Check the code at that line and see where the overflow could have been caused. In the case of the example above, calling the factorial with k+1 will cause an infinite loop which caused the overflow.

NoClassDefFound (Could not find or load main class ...)

Error when trying to run a java program but it cannot find the the Class with the main method.

A common cause of this error is putting .java at the end of the java command.

The below series of commands…

javac wiki.java

java wiki.java

… Results in

Error: Could not find or load main class wiki.java

The Class is wiki, not wiki.java so when trying to run the program it is unable to find the Class wiki where the main method is located.

To resolve the error, take out the .java when trying to run the program.

NoSuchMethodFoundError: main (Could not find or load main class ...)

Error occurring when trying to execute a class file that has no main method.

For example, say wiki.java has no main method. Barring no compile-time errors, the class file will compile. If executed, the following error will occur:

Error: Could not find or load main class wiki.java

To resolve the error, do not try to execute a class file that has no main method.

java_errors.txt · Last modified: 2013/08/05 13:08 by jhuber