Error invalid method declaration return type required java

We are learning how to use multiple classes in Java now, and there is a project asking about creating a class Circle which will contain a radius and a diameter, then reference it from a main class to

As you can see, the code public Circle(double r)…. how is that
different from what I did in mine with public CircleR(double r)? For
whatever reason, no error is given in the code from the book, however
mine says there is an error there.

When defining constructors of a class, they should have the same name as its class.
Thus the following code

public class Circle
{ 
    //This part is called the constructor and lets us specify the radius of a  
    //particular circle. 
  public Circle(double r) 
  { 
   radius = r; 
  }
 ....
} 

is correct while your code

public class Circle
{
    private double radius;
    public CircleR(double r)
    {
        radius = r;
    }
    public diameter()
    {
       double d = radius * 2;
       return d;
    }
}

is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from

public CircleR(double r) 

to

public Circle(double r)

or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.

So your new class should be

public class CircleR
{
    private double radius;
    public CircleR(double r)
    {
        radius = r;
    }
    public double diameter()
    {
       double d = radius * 2;
       return d;
    }
}

I also added the return type double in your method as pointed out by Froyo and John B.

Refer to this article about constructors.

HTH.

In this post, we will see how to resolve invalid method declaration; return type required.

There can be multiple reasons for invalid method declaration; return type required issue.

Table of Contents

  • Missing method return type
    • Solution
  • Missing comma in enum
    • Solution
  • Using different name for constructor
    • Solution

Missing method return type

It is quite clear from error message that you are missing return type of the method. If you don’t want to return anything from the method, then you should set it’s return type of void.

Let’s understand with the help of example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

package org.arpit.java2blog;

public class Employee {

    String name;

    int age;

    public Employee(String name) {

        this.name = name;

    }

    public setEmployeeDetails(String name,int age)

    {

        this.name=name;

        this.age=age;

    }

}

You will get compilation error at line 13 with error invalid method declaration; return type required.

Solution

In method setEmployeeDetails(), we did not specified return type. If it is not returning anything then its return type should be void.

Let’s change following line
public setEmployeeDetails(String name,int age)
to
public void setEmployeeDetails(String name,int age)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

package org.arpit.java2blog;

public class Employee {

    String name;

    int age;

    public Employee(String name) {

        this.name = name;

    }

    public void setEmployeeDetails(String name,int age)

    {

        this.name=name;

        this.age=age;

    }

}

Above code should compile fine now.

Missing comma in enum

This might sound strange but you can get this error when you are missing comma between enum type.

Let’s see with the help of example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package org.arpit.java2blog;

public enum Number {

        One(1);

        Two(2);

    private final int num;

    Number(int i) {;

        this.num=i;

    }

    public int getNumber() {

        return num;

    }

}

C:UsersArpitDesktop>javac Number.java
Number.java:6: error: invalid method declaration; return type required
Two(2);
^
Number.java:6: error: illegal start of type
Two(2);
^
2 errors

Solution

If you notice enum types are not separated by the comma and this is the reason for this error.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package org.arpit.java2blog;

public enum Number {

        One(1),

        Two(2);

    private final int num;

    Number(int i) {;

        this.num=i;

    }

    public int getNumber() {

        return num;

    }

}

C:UsersArpitDesktop>javac Number.java

C:UsersArpitDesktop>

As you can see error is resolved now.

Using different name for constructor

As you might know that constructor name should be same as class name in java. You might have put different name in constructor.
Let’s understand with the help of example:

package org.arpit.java2blog;

public class Employee {

    String name;

    int age;

    public EmployeeN(String name) {

        this.name = name;

    }

}

You will get compilation error at line 9 with error invalid method declaration; return type required.

Solution

As you can see, constructor name is different than class name.
Let’s change following line
public EmployeeN(String name) {
to
public Employee(String name) {
This will fix compilation error.

That’s all about invalid method declaration; return type required in java.

Fix Java Invalid Method Declaration; Return Type Required

Invalid method declaration; return type required. This type of error occurs in Java when you declare a function and don’t mention its return type.

Let’s follow up on the basics of functions and methods in Java.

Fix Invalid method declaration; return type required in Java

You need to understand how to name and define methods in Java.

Let’s take a simple example of declaring a function. Our function will add two numbers, and it will return the answer, which will be of an integer value.

public int addTwoNumbers(int a, int b)
{
    return a+b;
}

public is a reserved keyword in Java used to tell the member’s access. In this instance, it is public.

This keyword is followed by the return type of the method/function. In this case, it is int. Then you write the function’s name, and it can be any word of your choice provided it’s not a reserved keyword.

The above function will work just fine, and you will not receive any errors. But the error invalid method declaration; return type required occurs when you miss adding the function’s return type.

You can solve this by writing void instead of the return type. The void suggests that the function will not return any value.

Avoid the following code:

public void displaystring(String A)
{
    System.out.println(A);
    return A;//wrong way
}

As the above method is a void function, it cannot return a value. When you need to perform certain tasks, you use void functions, but you don’t require any value.

The correct way to write the above code is given below.

public void displaystring(String A)
{
    System.out.println(A);
}

Here’s the complete self-explanatory code.

public class Main 
{
    public static void main(String args[]) 
    {
     
       // invalid method declaration; return type required  This 
       // Error Occurs When you Declare A function did not mention any return type.

       // there are only two options.
            // if Function Did Not Return Any Value  void Keyword should be used.
            // void function always tell the compiler this function will return nothing..
         Print();
         Print1();
    }
// e.g of void function...........
 public static void Print()
 {
    System.out.println(" I am Void Function");
 }
// e.g of non void Function............

    public static int Print1()
    {
        System.out.println(" I am Non Void Function");
        return 3;
    }
}

Output:

I am Void Function
I am Non Void Function

In this post, I will be sharing how to fix invalid method declaration; return type required error. This error is mostly faced by Java beginners. This error generally occurs when the name of the constructor is different from the name of the class or missing method return type. Let’s dive deep into the topic:

Read Also:

Error: Identifier expected

[Fixed] Error: invalid method declaration; return type required

Example 1: Producing the error by using a different name for the constructor

Consider the following code:

public class HelloWorld {
    

public HelloWorld1(){

} public static void main(String args[]) { System.out.println("Constructor name is different than the Class name"); } }

When you compile the above code, you will get the following compilation error:


Output:
/HelloWorld.java:3: error: invalid method declaration; return type required
public HelloWorld1(){
           ^
1 error

Explanation

If you observe the code, then you will find that the name of the constructor is different from the name of the class. Hence, the compilation error. The above error can be fixed by defining the constructor having the same name as its class as shown below.

Solution

public class HelloWorld {
    

public HelloWorld(){

} public static void main(String args[]) { System.out.println("Constructor name is different than the Class name"); } }

Output:
Constructor name is different than the Class name

Example 2: Producing the error by missing method return type

Consider the following code:

public class HelloWorld {

    // Missing return type  

public printName(){

System.out.println("JavaHungry"); } public static void main(String args[]) { HelloWorld obj = new HelloWorld(); obj.printName(); } }

When you will compile the above code using the javac command, you will get the following compilation error:

Output:
/HelloWorld.java:4: error: invalid method declaration; return type required
public printName(){
           ^
1 error

Explanation

If you observe the code, then you will find that the return type of the method printName() is missing. Hence, the compilation error. The above error can be fixed by adding the return type in the method signature. Since method printName() does not return anything, hence, its return type is void.

Solution

public class HelloWorld {

public void printName(){

System.out.println("JavaHungry"); } public static void main(String args[]) { HelloWorld obj = new HelloWorld(); obj.printName(); } }

Output:
JavaHungry

Example 3: Producing the error by missing comma in enum

Consider the below code:

public class EnumExample {
    public enum Company {

APPLE("iPhone");

SAMSUNG("Galaxy"); private final String model; private Company(String model) { this.model = model; } } public static void main(String args[]){ for(Company c : Company.values()) System.out.println(c); } }

When you compile the above class using the javac command i.e javac EnumExample.java, then you will find the following compilation error:

Output:
/EnumExample.java:4: error: invalid method declaration; return type required
SAMSUNG(«Galaxy»);
^
/EnumExample.java:4: error: illegal start of type
SAMSUNG(«Galaxy»);
                     ^
2 errors

Explanation

If you observe the code, then you will find that the comma is missing in the enum Company. Since enum types should be separated by the comma, that is not the case here. Hence, the compilation error. The above error can be fixed by adding the comma in the enum as shown below.

Solution

public class EnumExample {
    public enum Company {

APPLE("iPhone"),

SAMSUNG("Galaxy"); private final String model; private Company(String model) { this.model = model; } } public static void main(String args[]){ for(Company c : Company.values()) System.out.println(c); } }




Output:

APPLE
SAMSUNG

That’s all for today, please mention in the comments in case you know any other way of solving invalid method declaration; return type required error.

Содержание

  1. Top 8 Common Java Errors for Beginners — and How to Solve Them
  2. Tue Jun 8 2021 by Matthew Wallace
  3. Syntax Errors
  4. Working with semicolons (;)
  5. Braces or parentheses [(), <>]
  6. Double Quotes or Quotation Marks (“ ”)
  7. Other Miscellaneous Errors
  8. Accessing the “Un-Initialized” Variables
  9. Accessing the “Out of Scope” Variables
  10. Modifying the “CONSTANT” Values
  11. Misinterpretted Use of Operators ( == vs .equals())
  12. Accessing a non-static resource from a static method
  13. Conclusion
  14. 50 Common Java Errors and How to Avoid Them
  15. Bogged down with Java errors? This series presents the 50 most common compiler errors and runtime exceptions that Java devs face, and how to conquer them.
  16. 1. “… Expected”
  17. 2. “Unclosed String Literal”
  18. 3. “Illegal Start of an Expression”
  19. 4. “Cannot Find Symbol”
  20. 5. “Public Class XXX Should Be in File”
  21. 6. “Incompatible Types”
  22. 7. “Invalid Method Declaration; Return Type Required”
  23. 8. “Method in Class Cannot Be Applied to Given Types”
  24. 9. “Missing Return Statement”
  25. 10. “Possible Loss of Precision”
  26. 11. “Reached End of File While Parsing”
  27. 12. “Unreachable Statement”
  28. 13. “Variable Might Not Have Been Initialized”
  29. 14. “Operator . Cannot be Applied to ”
  30. 15. “Inconvertible Types”
  31. 16. “Missing Return Value”
  32. 17. “Cannot Return a Value From Method Whose Result Type Is Void”
  33. 18. “Non-Static Variable . Cannot Be Referenced From a Static Context”
  34. 19. “Non-Static Method . Cannot Be Referenced From a Static Context”
  35. 20. “(array) Not Initialized”
  36. 21. “ArrayIndexOutOfBoundsException”
  37. 23. “NullPointerException”
  38. 24. “NoClassDefFoundError”
  39. 25. “NoSuchMethodFoundError”
  40. 26. “NoSuchProviderException”
  41. 27. AccessControlException
  42. 28. “ArrayStoreException”
  43. 29. “Bad Magic Number”
  44. 30. “Broken Pipe”
  45. 31. “Could Not Create Java Virtual Machine”
  46. 32. “class file contains wrong class”
  47. 33. “ClassCastException”

Top 8 Common Java Errors for Beginners — and How to Solve Them

Tue Jun 8 2021 by Matthew Wallace

Did you know that in Java’s standard library, there are a total of more than 500 different exceptions! There lots of ways for programmers to make mistakes — each of them unique and complex. Luckily we’ve taken the time to unwrap the meaning behind many of these errors, so you can spend less time debugging and more time coding. To begin with, let’s have a look at the syntax errors!

Syntax Errors

If you just started programming in Java, then syntax errors are the first problems you’ll meet! You can think of syntax as grammer in English. No joke, syntax errors might look minimal or simple to bust, but you need a lot of practice and consistency to learn to write error-free code. It doesn’t require a lot of math to fix these, syntax just defines the language rules. For further pertinent information, you may refer to java syntax articles.

Working with semicolons (;)

Think of semi-colons (;) in Java as you think of a full-stop (.) in English. A full stop tells readers the message a sentence is trying to convey is over. A semi-colon in code indicates the instruction for that line is over. Forgetting to add semi-colons (;) at the end of code is a common mistake beginners make. Let’s look at a basic example.

This snippet will produce the following error:

You can resolve this error by adding a ; at the end of line 3.

Braces or parentheses [(), <>]

Initially, it can be hard keeping a track of the starting / closing parenthesis or braces. Luckily IDEs are here to help. IDE stands for integrated development environment, and it’s a place you can write and run code. Replit for example, is an IDE. Most IDEs have IntelliSense, which is auto-complete for programmers, and will add closing brackets and parentheses for you. Despite the assistance, mistakes happen. Here’s a quick example of how you can put an extra closing bracket or miss the ending brace to mess up your code.

If you try to execute this, you’ll get the following error.

You can resolve this exception by removing the extra ) on line 9.

Double Quotes or Quotation Marks (“ ”)

Another pit fall is forgetting quotation marks not escaping them propperly. The IntelliSense can rescue you if you forget the remaining double quotes. If you try including quotation marks inside strings, Java will get confused. Strings are indicated using quotation marks, so having quotation marks in a string will make Java think the string ended early. To fix this, add a backslash () before quotation marks in strings. The backslash tells Java that this string should not be included in the syntax.

In order for you avoid such exceptions, you can add backslahes to the quotes in the string on line 4.

Here’s your required output, nicely put with double quotes! 🙂

Other Miscellaneous Errors

Accessing the “Un-Initialized” Variables

If you’re learning Java and have experience with other programming languages (like C++) then you might have a habit of using un-initialized variables (esp integers). Un-initialized variables are declared variables without a value. Java regulates this and doesn’t allow using a variable that has not been initialized yet.

If you attempt to access an uninitialized variable then you’ll get the following exception.

You can initialize the variable “contactNumber” to resolve this exception.

Accessing the “Out of Scope” Variables

If you define a variable in a certain method you’re only allowed to access that in the defined scope of it. Like each state has their legitimate currency, and that cannot be used in another state. You cannot use GBP in place of USD in America. Similarly, a variable defined in one method has restricted scope to it. You cannot access a local variable defined in some function in the main method. For further detailed illustration let’s look at an example.

As soon as you run this snippet, you’ll get the exception

You can not access the variable “country” outside the method getPersonalDetails since its scope is local.

Modifying the “CONSTANT” Values

Java and other programming languages don’t allow you to update or modify constant variables. You can use the keyword “final” before a variable to make it constant in Java. Apart from that, it’s a convention to write a constant in ALL CAPS for distinction purposes, As a constant resource is often used cross methods across a program.

Remove line 4 for the perfectly functional code.

Misinterpretted Use of Operators ( == vs .equals())

A lot of beginners start working with integers while learning the basics of a programming language. So it can be a challenge to remember that for string comparisons we use the “.equals()” method provided by Java and not == operator like in integers.

The output is contradictory because “today” and “thirdWeekDay” are referred to 2 different objects in the memory. However, the method “.equals()” compares the content stored in both arrays and returns true if it’s equal, false otherwise.

Accessing a non-static resource from a static method

If you want to access a non-static variable from a static method [let’s say the main method] then you need to create an instance of that object first. But if you fail to do that, java will get angry.

You can fix it, just by replacing line 9.

Conclusion

Programming errors are a part of the learning curve. Frequent errors might slow you down. But as a new programmer, it’s okay to learn things slowly. Now you’re familiar with some of the most common issues. Make sure you practise enough to get ahead of them. Happy coding and keep practising! 🙂

Источник

50 Common Java Errors and How to Avoid Them

Bogged down with Java errors? This series presents the 50 most common compiler errors and runtime exceptions that Java devs face, and how to conquer them.

Join the DZone community and get the full member experience.

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 and exceptions, complete with code examples and tutorials to help you work around common coding 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.

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. 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 (“”).

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. It is in these statements that the error can be found.

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 creates this issue.

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:

To fix this issue:

  • Name the class and file the same.
  • Make sure the case of both names is consistent.

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.

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.

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.

8. “Method in Class 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.

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.

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.

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.

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.

13. “Variable 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.

14. “Operator . Cannot be Applied to ”

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.

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.

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.

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:

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:

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.

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.

20. “(array) Not Initialized”

You’ll get the “(array) 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:

21. “ArrayIndexOutOfBoundsException”

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:

Array indexes start at zero and end at one less than the length of the array. Often it is fixed by using “

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.

23. “NullPointerException”

A “NullPointerException” will occur when the program tries to use an object reference that does not have a value assigned to it.

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.

24. “NoClassDefFoundError”

The “NoClassDefFoundError” will occur when the interpreter cannot find the file containing a class with the main method. Here’s an example from 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.

25. “NoSuchMethodFoundError”

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:

Often the “NoSuchMethodFoundError” Java software error occurs when there is a typo in the declaration.

26. “NoSuchProviderException”

“NoSuchProviderException” occurs when a security provider is requested that is not available:

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.

27. AccessControlException

AccessControlException indicates that requested access to system resources such as a file system or network is denied, as in this example from JBossDeveloper:

28. “ArrayStoreException”

An “ArrayStoreException” occurs when the rules of casting elements in Java arrays are broken. Arrays are very careful about what can go into them. For instance, this example from JavaScan.com illustrates that this program:

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 to be of the same type of object.

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:

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.

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.

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.

31. “Could Not Create Java Virtual Machine”

This Java error message usually occurs when the code tries to invoke Java with the wrong arguments:

It often is caused by a mistake in the declaration in the code or allocating the proper amount of memory to it.

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.

33. “ClassCastException”

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:

Источник

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 and exceptions, complete with code examples and tutorials to help you work around common coding problems.

1. “… Expected”

This error occurs when something is missing from the code. Often this is created by a missing semicolon or closing parenthesis.

private static double volume(String solidom, double alturam, double areaBasem, double raiom) {
double vol;

    if (solidom.equalsIgnoreCase("esfera"){
        vol=(4.0/3)*Math.pi*Math.pow(raiom,3);
    }
    else {
        if (solidom.equalsIgnoreCase("cilindro") {
            vol=Math.pi*Math.pow(raiom,2)*alturam;
        }
        else {
            vol=(1.0/3)*Math.pi*Math.pow(raiom,2)*alturam;
        }
    }
    return vol;
}

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.

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. A literal is a source code of a value.

 public abstract class NFLPlayersReference {

    private static Runningback[] nflplayersreference;

    private static Quarterback[] players;

    private static WideReceiver[] nflplayers;

    public static void main(String args[]){

    Runningback r = new Runningback("Thomlinsion");

    Quarterback q = new Quarterback("Tom Brady");

    WideReceiver w = new WideReceiver("Steve Smith");

    NFLPlayersReference[] NFLPlayersReference;


        Run();// {

        NFLPlayersReference = new NFLPlayersReference [3];

        nflplayersreference[0] = r;

        players[1] = q;

        nflplayers[2] = w;


            for ( int i = 0; i < nflplayersreference.length; i++ ) {

            System.out.println("My name is " + " nflplayersreference[i].getName());

            nflplayersreference[i].run();

            nflplayersreference[i].run();

            nflplayersreference[i].run();

            System.out.println("NFL offensive threats have great running abilities!");

        }

    }

    private static void Run() {

        System.out.println("Not yet implemented");

    }     

}

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.

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. It is in these statements that the error can be found.

} // ADD IT HERE

       public void newShape(String shape) {

        switch (shape) {
            case "Line":
                Shape line = new Line(startX, startY, endX, endY);
            shapes.add(line);
            break;
                case "Oval":
            Shape oval = new Oval(startX, startY, endX, endY);
            shapes.add(oval);
            break;
            case "Rectangle":
            Shape rectangle = new Rectangle(startX, startY, endX, endY);
            shapes.add(rectangle);
            break;
            default:
            System.out.println("ERROR. Check logic.");
        }
        }
    } // REMOVE IT FROM HERE
    }

Browse discussions of how to troubleshoot the “illegal start of an expression” error. 

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.

"cannot find symbol" Java software error

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 creates this issue.

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:

package javaapplication3;  


  public class Robot {  
        int xlocation;  
        int ylocation;  
        String name;  
        static int ccount = 0;  

        public Robot(int xxlocation, int yylocation, String nname) {  
            xlocation = xxlocation;  
            ylocation = yylocation;  
            name = nname;  
            ccount++;         
        } 
  }

  public class JavaApplication1 { 



    public static void main(String[] args) {  

        robot firstRobot = new Robot(34,51,"yossi");  
        System.out.println("numebr of robots is now " + Robot.ccount);  
    }
  }

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. 

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. 

test.java:78: error: incompatible types
return stringBuilder.toString();
                             ^
required: int
found:    String
1 error

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.” 

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.

public class Circle
{
    private double radius;
    public CircleR(double r)
    {
        radius = r;
    }
    public diameter()
    {
       double d = radius * 2;
       return d;
    }
}

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. 

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.

RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;
generateNumbers();

required: int[]

found:generateNumbers();

reason: actual and formal argument lists differ in length

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.

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.

public String[] OpenFile() throws IOException {

    Map<String, Double> map = new HashMap();

    FileReader fr = new FileReader("money.txt");
    BufferedReader br = new BufferedReader(fr);


    try{
        while (br.ready()){
            String str = br.readLine();
            String[] list = str.split(" ");
            System.out.println(list);               
        }
    }   catch (IOException e){
        System.err.println("Error - IOException!");
    }
}

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.

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.

"possible loss of precision" error in Java

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. 

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.

public class mod_MyMod extends BaseMod
public String Version()
{
     return "1.2_02";
}
public void AddRecipes(CraftingManager recipes)
{
   recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
      "#", Character.valueOf('#'), Block.dirt
   });
}

The above code results in the following error:

java:11: reached end of file while parsing }

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.

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.

for(;;){
   break;
   ... // unreachable statement
}


int i=1;
if(i==1)
  ...
else
  ... // dead code

Often simply moving the return statement will fix the error. Read the discussion of how to fix unreachable statement Java software error. 

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.

int x;
if (condition) {
    x = 5;
}
System.out.println(x); // x may not have been initialized

Read this discussion of how to avoid triggering the “variable <X> might not have been initialized” error. 

14. “Operator … Cannot be Applied to <X>”

This issue occurs when operators are used for types not in their definition.

operator < cannot be applied to java.lang.Object,java.lang.Object

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.

15. “Inconvertible Types”

The “inconvertible types” error occurs when the Java code tries to perform an illegal conversion.

TypeInvocationConversionTest.java:12: inconvertible types
found   : java.util.ArrayList<java.lang.Class<? extends TypeInvocationConversionTest.Interface1>>
required: java.util.ArrayList<java.lang.Class<?>>
    lessRestrictiveClassList = (ArrayList<Class<?>>) classList;
                                                     ^

For example, booleans cannot be converted to an integer.

Read this discussion about finding ways to convert inconvertible types in Java software.

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:

public class SavingsAcc2 {
    private double balance;
    private double interest;


    public SavingsAcc2() {
        balance = 0.0;
        interest = 6.17;
    }

    public SavingsAcc2(double initBalance, double interested) {
        balance = initBalance;
        interest = interested;

    }

    public SavingsAcc2 deposit(double amount) {
        balance = balance + amount;
        return;
    }

    public SavingsAcc2 withdraw(double amount) {
        balance = balance - amount;
        return;
    }

    public SavingsAcc2 addInterest(double interest) {
        balance = balance * (interest / 100) + balance;
        return;
    }

    public double getBalance() {
        return balance;
    }
}

Returns the following error:

SavingsAcc2.java:29: missing return value 
return; 
^ 
SavingsAcc2.java:35: missing return value 
return; 
^ 
SavingsAcc2.java:41: missing return value 
return; 
^ 
3 errors 

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. 

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:

public static void move()
{
    System.out.println("What do you want to do?");
    Scanner scan = new Scanner(System.in);
    int userMove = scan.nextInt();
    return userMove;
}

public static void usersMove(String playerName, int gesture)
{
    int userMove = move();

    if (userMove == -1)
    {
        break;
    }

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:

public static int move()
{
    System.out.println("What do you want to do?");
    Scanner scan = new Scanner(System.in);
    int userMove = scan.nextInt();
    return userMove;
}

Read this discussion about how to fix the “cannot return a value from method whose result type is void” error. 

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:

public class StaticTest {

    private int count=0;
    public static void main(String args[]) throws IOException {
        count++; //compiler error: non-static variable count cannot be referenced from a static context
    }
}

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.

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:

class Sample
{
   private int age;
   public void setAge(int a)
   {
      age=a;
   }
   public int getAge()
   {
      return age;
   }
   public static void main(String args[])
   {
       System.out.println("Age is:"+ getAge());
   }
}

Would return this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Cannot make a static reference to the non-static method getAge() from the type Sample

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:

AClass[] array = {object1, object2}

As is:

AClass[] array = new AClass[2];
...
array[0] = object1;
array[1] = object2;

But not:

AClass[] array;
...
array = {object1, object2};

Read this discussion of how to initialize arrays in Java software.

21. “ArrayIndexOutOfBoundsException”

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:

String[] name = {
    "tom",
    "dick",
    "harry"
};
for (int i = 0; i <= name.length; i++) {
    System.out.print(name[i] + 'n');
}

Here’s another example:

int[] list = new int[5];
list[5] = 33; // illegal index, maximum index is 4

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. 

22. “StringIndexOutOfBoundsException”

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:

public class StringCharAtExample {
    public static void main(String[] args) {
        String str = "Java Code Geeks!";
        System.out.println("Length: " + str.length());

        //The following statement throws an exception, because
        //the request index is invalid.
        char ch = str.charAt(50);
    }
}

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.

23. “NullPointerException”

A “NullPointerException” will occur when the program tries to use an object reference that does not have a value assigned to it.

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.

24. “NoClassDefFoundError”

The “NoClassDefFoundError” will occur when the interpreter cannot find the file containing a class with the main method. Here’s an example from DZone:

// A Java program to demonstrate that invoking a method
// on null causes NullPointerException
import java.io.*;

class GFG
{
    public static void main (String[] args)
    {
        // Initializing String variable with null value
        String ptr = null;

        // Checking if ptr.equals null or works fine.
        try
        {
            // This line of code throws NullPointerException
            // because ptr is null
            if (ptr.equals("gfg"))
                System.out.print("Same");
            else
                System.out.print("Not Same");
        }
        catch(NullPointerException e)
        {
            System.out.print("NullPointerException Caught");
        }
    }
}

If you compile this program:

class A
{
  // some code
}
public class B
{
    public static void main(String[] args)
    {
        A a = new A();
    }

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:

Exception in thread "main" java.lang.NoClassDefFoundError: A
at MainClass.main(MainClass.java:10)
Caused by: java.lang.ClassNotFoundException: A
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

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. 

25. “NoSuchMethodFoundError”

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:

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

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.” 

26. “NoSuchProviderException”

“NoSuchProviderException” occurs when a security provider is requested that is not available:

javax.mail.NoSuchProviderException

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. 

27. AccessControlException

AccessControlException indicates that requested access to system resources such as a file system or network is denied, as in this example from JBossDeveloper:

ERROR Could not register mbeans java.security.

AccessControlException: WFSM000001: Permission check failed (permission "("javax.management.MBeanPermission" "org.apache.logging.log4j.core.jmx.LoggerContextAdmin#-
[org.apache.logging.log4j2:type=51634f]" "registerMBean")" in code source "(vfs:/C:/wildfly-10.0.0.Final/standalone/deployments/mySampleSecurityApp.war/WEB-INF/lib/log4j-core-2.5.
jar )" of "null")

Read this discussion of a workaround used to get past an “AccessControlException” error. 

28. “ArrayStoreException”

An “ArrayStoreException” occurs when the rules of casting elements in Java arrays are broken. Arrays are very careful about what can go into them. For instance, this example from JavaScan.com illustrates that this program:

 /* ............... START ............... */

 public class JavaArrayStoreException {

     public static void main(String...args) {
         Object[] val = new Integer[4];
         val[0] = 5.8;
     }

 }
 /* ............... END ............... */

Results in the following output:

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double
at ExceptionHandling.JavaArrayStoreException.main(JavaArrayStoreException.java:7)

When an array is initialized, the sorts of objects allowed into the array need to be declared. Then each array element needs to be of the same type of object.

Read this discussion of how to solve for the “ArrayStoreException.”

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:

Java(TM) Plug-in: Version 1.3.1_01
Using JRE version 1.3.1_01 Java HotSpot(TM) Client VM
User home directory = C:Documents and SettingsAnkur

Proxy Configuration: Manual Configuration

Proxy: 192.168.11.6:80

java.lang.ClassFormatError: SalesCalculatorAppletBeanInfo (Bad magic number)

at java.lang.ClassLoader.defineClass0(Native Method)

at java.lang.ClassLoader.defineClass(Unknown Source)

at java.security.SecureClassLoader.defineClass(Unknown Source)

at sun.applet.AppletClassLoader.findClass(Unknown Source)

at sun.plugin.security.PluginClassLoader.access$201(Unknown Source)

at sun.plugin.security.PluginClassLoader$1.run(Unknown Source)

at java.security.AccessController.doPrivileged(Native Method)

at sun.plugin.security.PluginClassLoader.findClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.applet.AppletClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at java.beans.Introspector.instantiate(Unknown Source)

at java.beans.Introspector.findInformant(Unknown Source)

at java.beans.Introspector.(Unknown Source)

at java.beans.Introspector.getBeanInfo(Unknown Source)

at sun.beans.ole.OleBeanInfo.(Unknown Source)

at sun.beans.ole.StubInformation.getStub(Unknown Source)

at sun.plugin.ocx.TypeLibManager$1.run(Unknown Source)

at java.security.AccessController.doPrivileged(Native Method)

at sun.plugin.ocx.TypeLibManager.getTypeLib(Unknown Source)

at sun.plugin.ocx.TypeLibManager.getTypeLib(Unknown Source)

at sun.plugin.ocx.ActiveXAppletViewer.statusNotification(Native Method)

at sun.plugin.ocx.ActiveXAppletViewer.notifyStatus(Unknown Source)

at sun.plugin.ocx.ActiveXAppletViewer.showAppletStatus(Unknown Source)

at sun.applet.AppletPanel.run(Unknown Source)

at java.lang.Thread.run(Unknown Source)

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.”

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.

Exception in thread "main" java.net.SocketException: Broken pipe
      at java.net.SocketOutputStream.socketWrite0(Native Method)
      at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
      at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
      at java.io.DataOutputStream.write

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.”

31. “Could Not Create Java Virtual Machine”

This Java error message usually occurs when the code tries to invoke Java with the wrong arguments:

Error: Could not create the Java Virtual Machine

Error: A fatal exception has occurred. Program will exit.

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.” 

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:

MyTest.java:10: cannot access MyStruct 
bad class file: D:JavatestMyStruct.java 
file does not contain class MyStruct 
Please remove or make sure it appears in the correct subdirectory of the classpath. 
MyStruct ms = new MyStruct(); 
^ 

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.

33. “ClassCastException”

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:

package com;
class A
{
    int i = 10;
}

class B extends A
{
    int j = 20;
}

class C extends B
{
    int k = 30;
}

public class ClassCastExceptionDemo
{
    public static void main(String[] args)
    {
        A a = new B();   //B type is auto up casted to A type
        B b = (B) a;     //A type is explicitly down casted to B type.
        C c = (C) b;    //Here, you will get class cast exception
        System.out.println(c.k);
    }
}

Results in this error:

Exception in thread “main” java.lang.ClassCastException: com.B cannot be cast to com.C

at com.ClassCastExceptionDemo.main(ClassCastExceptionDemo.java:23)

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.

34. “ClassFormatError”

The “ClassFormatError” message indicates a linkage error and occurs when a class file cannot be read or interpreted as a class file.

Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is
        not native or abstract in class file javax/persistence/GenerationType

at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)

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. 

35. “ClassNotFoundException”

“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” for more cases. 

36. “ExceptionInInitializerError”

This Java issue will occur when something goes wrong with a static initialization. When the Java code later uses the class, the “NoClassDefFoundError” error will occur.

java.lang.ExceptionInInitializerError
  at org.eclipse.mat.hprof.HprofIndexBuilder.fill(HprofIndexBuilder.java:54)
  at org.eclipse.mat.parser.internal.SnapshotFactory.parse(SnapshotFactory.java:193)
  at org.eclipse.mat.parser.internal.SnapshotFactory.openSnapshot(SnapshotFactory.java:106)
  at com.squareup.leakcanary.HeapAnalyzer.openSnapshot(HeapAnalyzer.java:134)
  at com.squareup.leakcanary.HeapAnalyzer.checkForLeak(HeapAnalyzer.java:87)
  at com.squareup.leakcanary.internal.HeapAnalyzerService.onHandleIntent(HeapAnalyzerService.java:56)
  at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:145)
  at android.os.HandlerThread.run(HandlerThread.java:61)
Caused by: java.lang.NullPointerException: in == null
  at java.util.Properties.load(Properties.java:246)
  at org.eclipse.mat.util.MessageUtil.(MessageUtil.java:28)
  at org.eclipse.mat.util.MessageUtil.(MessageUtil.java:13)
  ... 10 more

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.

37. “IllegalBlockSizeException”

An “IllegalBlockSizeException” will occur during decryption when the length message is not a multiple of 8 bytes. Here’s an example from ProgramCreek.com.

@Override
protected byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
    try {
        byte[] encoded = key.getEncoded();
        return engineDoFinal(encoded, 0, encoded.length);
    } catch (BadPaddingException e) {
        IllegalBlockSizeException newE = new IllegalBlockSizeException();
        newE.initCause(e);
        throw newE;
    }
}

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.

38. “BadPaddingException”

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:

javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)

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.

39. “IncompatibleClassChangeError”

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:

Exception in thread "main" java.lang.IncompatibleClassChangeError: Implementing class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at net.sf.cglib.core.DebuggingClassWriter.toByteArray(DebuggingClassWriter.java:73)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:26)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)

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.” 

40. “FileNotFoundException”

This Java software error message is thrown when a file with the specified pathname does not exist.

@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
    if (uri.toString().startsWith(FILE_PROVIDER_PREFIX)) {
        int m = ParcelFileDescriptor.MODE_READ_ONLY;
        if (mode.equalsIgnoreCase("rw")) m = ParcelFileDescriptor.MODE_READ_WRITE;
        File f = new File(uri.getPath());
        ParcelFileDescriptor pfd = ParcelFileDescriptor.open(f, m);
        return pfd;
    } else {
        throw new FileNotFoundException("Unsupported uri: " + uri.toString());
    }
}

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. 

41. “EOFException”

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:

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ExceptionExample {
    public void testMethod1() {
        File file = new File("test.txt");
        DataInputStream dataInputStream = null;
        try {
            dataInputStream = new DataInputStream(new FileInputStream(file));
            while (true) {
                dataInputStream.readInt();
            }
        } catch (EOFException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dataInputStream != null) {
                    dataInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        ExceptionExample instance1 = new ExceptionExample();
        instance1.testMethod1();
    }
}

Running the program above results in the following exception:

java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at logging.simple.ExceptionExample.testMethod1(ExceptionExample.java:16)
at logging.simple.ExceptionExample.main(ExceptionExample.java:36)

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.

42. “UnsupportedEncodingException”

This Java software error message is thrown when character encoding is not supported.

public UnsupportedEncodingException()

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.

43. “SocketException”

A “SocketException” indicates there is an error creating or accessing a socket:

public void init(String contextName, ContextFactory factory) {
    super.init(contextName, factory);

    String periodStr = getAttribute(PERIOD_PROPERTY);
    if (periodStr != null) {
        int period = 0;
        try {
            period = Integer.parseInt(periodStr);
        } catch (NumberFormatException nfe) {}
        if (period <= 0) {
            throw new MetricsException("Invalid period: " + periodStr);
        }
        setPeriod(period);
    }

    metricsServers =
        Util.parse(getAttribute(SERVERS_PROPERTY), DEFAULT_PORT);

    unitsTable = getAttributeTable(UNITS_PROPERTY);
    slopeTable = getAttributeTable(SLOPE_PROPERTY);
    tmaxTable = getAttributeTable(TMAX_PROPERTY);
    dmaxTable = getAttributeTable(DMAX_PROPERTY);

    try {
        datagramSocket = new DatagramSocket();
    } catch (SocketException se) {
        se.printStackTrace();
    }
}

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.

44. “SSLException”

This Java software error message occurs when there is failure in SSL-related operations. The following example is from Atlassian:

com.sun.jersey.api.client.ClientHandlerException: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
   at com.sun.jersey.client.apache.ApacheHttpClientHandler.handle(ApacheHttpClientHandler.java:202)
   at com.sun.jersey.api.client.Client.handle(Client.java:365)
   at com.sun.jersey.api.client.WebResource.handle(WebResource.java:556)
   at com.sun.jersey.api.client.WebResource.get(WebResource.java:178)
   at com.atlassian.plugins.client.service.product.ProductServiceClientImpl.getProductVersionsAfterVersion(ProductServiceClientImpl.java:82)
   at com.atlassian.upm.pac.PacClientImpl.getProductUpgrades(PacClientImpl.java:111)
   at com.atlassian.upm.rest.resources.ProductUpgradesResource.get(ProductUpgradesResource.java:39)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
   at java.lang.reflect.Method.invoke(Unknown Source)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper$ResponseOutInvoker$1.invoke(DispatchProviderHelper.java:206)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper$1.intercept(DispatchProviderHelper.java:90)
   at com.atlassian.plugins.rest.common.interceptor.impl.DefaultMethodInvocation.invoke(DefaultMethodInvocation.java:61)
   at com.atlassian.plugins.rest.common.expand.interceptor.ExpandInterceptor.intercept(ExpandInterceptor.java:38)
   at com.atlassian.plugins.rest.common.interceptor.impl.DefaultMethodInvocation.invoke(DefaultMethodInvocation.java:61)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper.invokeMethodWithInterceptors(DispatchProviderHelper.java:98)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper.access$100(DispatchProviderHelper.java:28)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper$ResponseOutInvoker._dispatch(DispatchProviderHelper.java:202)
   ...
Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
   ...
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
   ...
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

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.

45. “MissingResourceException”

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:

java.util.MissingResourceException: Can't find bundle for base name localemsgs_en_US, locale en_US
java.util.ResourceBundle.throwMissingResourceException
java.util.ResourceBundle.getBundleImpl
java.util.ResourceBundle.getBundle
net.sf.jasperreports.engine.util.JRResourcesUtil.loadResourceBundle
net.sf.jasperreports.engine.util.JRResourcesUtil.loadResourceBundle

Read this discussion of how to fix “MissingResourceException” while running Java software.

46. “NoInitialContextException”

A “NoInitialContextException” occurs when the Java application wants to perform a naming operation but can’t create a connection.

[java] Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
[java]     at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
[java]     at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
[java]     at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:284)
[java]     at javax.naming.InitialContext.lookup(InitialContext.java:351)
[java]     at org.apache.camel.impl.JndiRegistry.lookup(JndiRegistry.java:51)

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.

47. “NoSuchElementException”

A “NoSuchElementException” happens when an iteration (such as a “for” loop) tries to access the next element when there is none.

public class NoSuchElementExceptionDemo{

    public static void main(String args[]) {
        Hashtable sampleMap = new Hashtable();
        Enumeration enumeration = sampleMap.elements();
        enumeration.nextElement();  //java.util.NoSuchElementExcepiton here because enumeration is empty
    }
}

Output:
Exception in thread "main" java.util.NoSuchElementException: Hashtable Enumerator
        at java.util.Hashtable$EmptyEnumerator.nextElement(Hashtable.java:1084)
        at test.ExceptionTest.main(NoSuchElementExceptionDemo.java:23)

Exception in thread «main» java.util.NoSuchElementException: Hashtable Enumerator 

The “NoSuchElementException” can be thrown by these methods:

  • Enumeration::nextElement()

  • NamingEnumeration::next()

  • StringTokenizer::nextElement()

  • Iterator::next()

Read this tutorial on how to fix “NoSuchElementException” in Java software.

48. “NoSuchFieldError”

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.

public NoSuchFieldError()

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.

49. “NumberFormatException”

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.

package com.devdaily.javasamples;

public class ConvertStringToNumber {

    public static void main(String[] args) {
        try {
            String s = "FOOBAR";
            int i = Integer.parseInt(s);
            // this line of code will never be reached
            System.out.println("int value = " + i);
        }
        catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    }

}

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. 

50. “TimeoutException”

This Java software error message occurs when a blocking operation times out.

private void queueObject(ComplexDataObject obj) throws TimeoutException, InterruptedException {
    if (!queue.offer(obj, 10, TimeUnit.SECONDS)) {
        TimeoutException ex = new TimeoutException("Timed out waiting for parsed elements to be processed. Aborting.");
        throw ex;
    }
}

Read this discussion about how to handle “TimeoutException” when running Java software.

Conclusion

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 this article saved or otherwise bookmarked for quick recall. 

Java (programming language)
Data Types
Error message
Software
Strings
Literal (computer programming)
End-of-file

Понравилась статья? Поделить с друзьями:
  • Error invalid magic number ubuntu
  • Error invalid magic number error you need to load the kernel first
  • Error invalid magic number error please load the kernel first
  • Error invalid login при обновлении joomla 3
  • Error invalid license environment application closing