Error incompatible types java

The Java incompatible types error happens when a value assigned to a variable or returned by a method is incompatible with the one declared.

Introduction to Data Types & Type Conversion

Variables are memory containers used to store information. In Java, every variable has a data type and stores a value of that type. Data types, or types for short, are divided into two categories: primitive and non-primitive. There are eight primitive types in Java: byte, short, int, long, float, double, boolean and char. These built-in types describe variables that store single values of a predefined format and size. Non-primitive types, also known as reference types, hold references to objects stored somewhere in memory. The number of reference types is unlimited, as they are user-defined. A few reference types are already baked into the language and include String, as well as wrapper classes for all primitive types, like Integer for int and Boolean for boolean. All reference types are subclasses of java.lang.Object [1].

In programming, it is commonplace to convert certain data types to others in order to allow for the storing, processing, and exchanging of data between different modules, components, libraries, APIs, etc. Java is a statically typed language, and as such has certain rules and constraints in regard to working with types. While it is possible to convert to and from certain types with relative ease, like converting a char to an int and vice versa with type casting [2], it is not very straightforward to convert between other types, such as between certain primitive and reference types, like converting a String to an int, or one user-defined type to another. In fact, many of these cases would be indicative of a logical error and require careful consideration as to what is being converted and how, or whether the conversion is warranted in the first place. Aside from type casting, another common mechanism for performing type conversion is parsing [3], and Java has some predefined methods for performing this operation on built-in types.

double myDouble = 9; // Automatic casting (int to double)
int myInt = (int) 9.87d; // Manual casting (double to int)
boolean myBoolean = Boolean.parseBoolean("True"); // Parsing with a native method (String to boolean)

System.out.println(myDouble);   // 9.0
System.out.println(myInt);      // 9
System.out.println(myBoolean);  // true

Incompatible Types Error: What, Why & How?

The incompatible types error indicates a situation where there is some expression that yields a value of a certain data type different from the one expected. This error implies that the Java compiler is unable to resolve a value assigned to a variable or returned by a method, because its type is incompatible with the one declared on the variable or method in question. Incompatible, in this context, means that the source type is both different from and unconvertible (by means of automatic type casting) to the declared type.

This might seem like a syntax error, but it is a logical error discovered in the semantic phase of compilation. The error message generated by the compiler indicates the line and the position where the type mismatch has occurred and specifies the incompatible types it has detected. This error is a generalization of the method X in class Y cannot be applied to given types and the constructor X in class Y cannot be applied to given types errors discussed in [4].

The incompatible types error most often occurs when manual or explicit conversion between types is required, but it can also happen by accident when using an incorrect API, usually involving the use of an incorrect reference type or the invocation of an incorrect method with an identical or similar name.

Incompatible Types Error Examples

Explicit type casting

Assigning a value of one primitive type to another can happen in one of two directions. Either from a type of a smaller size to one of a larger size (upcasting), or from a larger-sized type to a smaller-sized type (downcasting). In the case of the former, the data will take up more space but will be intact as the larger type can accommodate any value of the smaller type. So the conversion here is done automatically. However, converting from a larger-sized type to a smaller one necessitates explicit casting because some data may be lost in the process.

Fig. 1(a) shows how attempting to assign the values of the two double variables a and b to the int variables x and y results in the incompatible types error at compile-time. Prefixing the variables on the right-hand side of the assignment with the int data type in parenthesis (lines 10 & 11 in Fig. 1(b)) fixes the issue. Note how both variables lost their decimal part as a result of the conversion, but only one kept its original value—this is exactly why the error message reads possible lossy conversion from double to int and why the incompatible types error is raised in this scenario. By capturing this error, the compiler prevents accidental loss of data and forces the programmer to be deliberate about the conversion. The same principle applies to downcasting reference types, although the process is slightly different as polymorphism gets involved [5].

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class IncompatibleTypesCasting {

  public static void main(String... args) {
    double a = 10.5;
    double b = 5.0;
    System.out.println("a: " + a + "tb: " + b);

    int x = a;
    int y = b;
    System.out.println("x: " + x + "ty: " + y);
  }
}
IncompatibleTypesCasting.java:10: error: incompatible types: possible lossy conversion from double to int
    int x = a;
            ^
IncompatibleTypesCasting.java:11: error: incompatible types: possible lossy conversion from double to int
    int y = b;
            ^
2 errors

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class IncompatibleTypesCasting {

  public static void main(String... args) {
    double a = 10.5;
    double b = 5.0;
    System.out.println("a: " + a + "tb: " + b);

    int x = (int) a;
    int y = (int) b;
    System.out.println("x: " + x + "ty: " + y);
  }
}
a: 10.5 b: 5.0
x: 10   y: 5
Figure 1: Incompatible types when downcasting (a) error and (b) resolution

Explicit parsing

Parsing is a more complex process than type casting as it involves analyzing the underlying structure of a given data before converting it into a specific format or type. For instance, programmers often deal with incoming streams of characters, usually contained in a string that needs to be converted into specific types to make use of in the code. A common scenario is extracting numeric values from a string for further processing, which is where parsing is routinely used.

The main method in Fig. 2(a) declares the variable date which holds the current date as a String in the yyyy-MM-dd format. In order to get the year value into a separate variable it is necessary to “parse” the first 4 characters of the string, and this can be accomplished by splitting the string by specifying the “-” character as a delimiter and then accessing the first element (line 9 in Fig. 2(a)). With this, the year value has been successfully parsed and stored into a new variable. Attempting to increase the value of this new variable and store the resulting value in a separate int variable triggers the incompatible types error (line 10 in Fig. 2(a)). This is because even though the year has been isolated from the date and parsed into a new variable, it is impossible to perform arithmetic operations on a variable of type String. Therefore, it is necessary to represent this value as a numeric type. The best way to do this is to use Java’s built-in Integer::parseInt method which takes a String argument and converts it to an int (line 10 in Fig. 2(b)). (Note that if the given argument is not a valid integer value, this method will throw an exception.) Now that the year has been manually and explicitly parsed from the initial date string into an integer value that can be incremented, the program compiles and prints the expected message, as shown in Fig. 2(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.time.LocalDate;

public class IncompatibleTypesParsing {

 public static void main(String... args) {
   String date = LocalDate.now().toString(); // "2021-12-21"
   String year = date.split("-")[0]; // "2021"
   int newYear = year + 1;
   System.out.println("Happy New Year " + newYear + "!");
 }
}
IncompatibleTypesParsing.java:10: error: incompatible types: String cannot be converted to int
    int newYear = year + 1;
                       ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.time.LocalDate;

public class IncompatibleTypesParsing {

  public static void main(String... args) {
    String date = LocalDate.now().toString();
    String year = date.split("-")[0];
    int newYear = Integer.parseInt(year) + 1;
    System.out.println("Happy New Year " + newYear + "!");
  }
}
Happy New Year 2022!
Figure 2: Incompatible types when parsing (a) error and (b) resolution

Incorrect type assignments

Sometimes, the incompatible types error can occur due to basic negligence, where the only mistake is an accidental mis-declaration of a variable’s type (Fig. 3(a)). In these instances, the issue is quite obvious and simply correcting the type declaration solves the problem (Fig. 3(b)).

(a)

package rollbar;

public class IncompatibleTypesAssignment {

 public static void main(String... args) {
   int greeting = "Merry Christmas!";
   System.out.println(greeting);
 }
}
IncompatibleTypesAssignment.java:6: error: incompatible types: String cannot be converted to int
    int greeting = "Merry Christmas!";
                   ^
1 error

(b)

package rollbar;

public class IncompatibleTypesAssignment {

 public static void main(String... args) {
   String greeting = "Merry Christmas!";
   System.out.println(greeting);
 }
}
Merry Christmas!
Figure 3: Incompatible types with incorrect assignment (a) error and (b) resolution

Incorrect method return types

A slightly less common but non-surprising occurence of the incompatible types error, especially when refactoring is involved, can be found in method return types. Namely, sometimes a method’s return statement ends up returning a value that doesn’t match the method’s declared return type (Fig. 4(a)). This issue has two possible remedies; either make the value returned match the return type (Fig. 4(b)), or change the method’s return type to match the actual value returned (Fig. 4(c)). And in the case of void methods (methods with no return type), one can simply get rid of the return statement if the return value is never used, as is the case with the example in Fig. 4.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static void printGreeting() {
   System.out.println("Happy Holidays");
   return true;
 }
}
IncompatibleTypesReturn.java:11: error: incompatible types: unexpected return value
    return true;
           ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static void printGreeting() {
   System.out.println("Happy Holidays");
 }
}
Happy Holidays!

(c)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static boolean printGreeting() {
   System.out.println("Happy Holidays");
   return true;
 }
}
Happy Holidays!
Figure 4: Incompatible types with incorrect return type (a) error and (b)(c) two solutions

Incorrect imports and similarly named reference types

It is not uncommon to come across classes or other reference types with the same or a similar name. In fact, this happens even within the standard Java API, and can baffle many programmers, beginners and experts alike. One such case is the List class which represents one of Java’s main collection data structures [6]. This reference type can easily come into collision with another type of the same name, but from a different package. Namely, that’s the java.awt.List class that is part of Java’s built-in AWT API for creating graphical user interfaces [7]. All it takes is accidentally importing the wrong package, and the compiler immediately complains about the type mismatch, raising the incompatible types error, as demonstrated in Fig. 5(a). Fixing the import on line 5, as shown in Fig. 5(b), sorts things out.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.awt.List;

public class IncompatibleTypesList {

 public static void main(String... args) {
   List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
   System.out.println(songs);
 }
}
IncompatibleTypesList.java:10: error: incompatible types: ArrayList<String> cannot be converted to List
    List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
                 ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IncompatibleTypesList {

 public static void main(String... args) {
   List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
   System.out.println(songs);
 }
}
[Silent Night, Deck the Halls, Jingle Bells, Winter Wonderland]
Figure 5: Incompatible types incorrect reference type (a) error and (b) resolution

Popular external libraries are also prone to naming their reference types similarly, so whenever relying on such a library for a certain feature or functionality it is important to pick one, or be careful not to confuse one for another, if multiple libraries are already being used.

Fig. 6(a) shows an example of passing a JSON type object to a method as an argument. Here, the method printJson expects an argument of type JsonObject, but the calling method tries to pass in an instance of the similarly named JSONObject reference type, part of a different library altogether. This results in the incompatible types error being raised by the compiler, with the alert org.json.JSONObject cannot be converted to javax.json.JsonObject pointing to the erroneous method call. Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import org.json.JSONObject;
import javax.json.JsonObject;
import java.util.Map;

public class IncompatibleTypesJson {

  public static void main(String... args) {
    Map<String, Object> jsonMap = Map.of(
        "name", "Saint Nicholas",
        "nicknames", new String[]{"Santa Claus", "Father Christmas"},
        "location", "North Pole"
    );

    JsonObject json = Json.createObjectBuilder(jsonMap).build();

    printJson(json);
}

  static void printJson(JSONObject jsonObject) {
    System.out.println(jsonObject.toString(4));
  }
}
IncompatibleTypesJson.java:18: error: incompatible types: 
javax.json.JsonObject cannot be converted to org.json.JSONObject
    printJson(json);
              ^

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import javax.json.Json;
import javax.json.JsonObject;
import java.util.Map;

public class IncompatibleTypesJson {

  public static void main(String... args) {
    Map<String, Object> jsonMap = Map.of(
        "name", "Saint Nicholas",
        "nicknames", new String[]{"Santa Claus", "Father Christmas"},
        "location", "North Pole"
    );

    JSONObject json = new JSONObject(jsonMap);

    printJson(json);
  }

  static void printJson(JSONObject jsonObject) {
    System.out.println(jsonObject.toString(4));
  }
}
{
    "name": "Saint Nicholas",
    "location": "North Pole",
    "nicknames": [
        "Santa Claus",
        "Father Christmas"
    ]
}
Figure 6: Incompatible types incorrect reference type (a) error and (b) resolution

Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4]. Depending on the specific compiler that is being used and its configuration settings, either of these errors could be triggered in this kind of scenario.

Summary

As a strongly typed language, Java has strict rules regarding data types and how they interoperate. These rules affect variable assignment, method invocation, return values, etc. This makes Java code verbose, but at the same time quite secure, as it allows for many errors to be detected during compilation. One such error is the incompatible types error, which is directly tied to Java’s type system. This article provides some background into Java types and dives into the symptoms and causes behind the incompatible types error, by presenting a series of relevant examples tailored to bring clarity in understanding and successfully managing this error.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] R. Liguori and P. Liguori, 2017. Java Pocket Guide, 4th ed. Sebastopol, CA: O’Reilly Media, pp. 23-46.

[2] W3schools.com, 2021. Java Type Casting. Refsnes Data. [Online]. Available: https://www.w3schools.com/java/java_type_casting.asp. [Accessed: Dec. 18, 2021]

[3] D. Capka, 2021. Lesson 3 — Variables, type system and parsing in Java, Ictdemy.com. [Online]. Available: https://www.ictdemy.com/java/basics/variables-type-system-and-parsing-in-java. [Accessed: Dec. 19, 2021]

[4] Rollbar, 2021. How to Fix Method/Constructor X in Class Y Cannot be Applied to Given Types in Java, Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-fix-method-constructor-in-class-cannot-be-applied-to-given-types-in-java/. [Accessed: Dec. 21, 2021]

[5] W3schools.com, 2021. Java Type Casting. Refsnes Data. [Online]. Available: https://www.w3schools.com/java/java_type_casting.asp. [Accessed: Dec. 21, 2021]

[6] Oracle.com, 2021. Lesson: Implementations (The Java™ Tutorials > Collections). [Online]. Available: https://docs.oracle.com/javase/tutorial/collections/implementations/index.html. [Accessed: Dec. 21, 2021]

[7] Oracle.com, 2020. Package java.awt (Java SE 15 & JDK 15). Oracle and/or its affiliates [Online]. Available: https://docs.oracle.com/en/java/javase/15/docs/api/java.desktop/java/awt/package-summary.html. [Accessed: Dec. 21, 2021]

This is basically the same case as posted previous. Basically, in a generics case, you are never allowed to do this assigment:

Think of this example:

ArrayList<Object> alist = new ArrayList<Number>();

This doesn’t compile because it is not type safe. You could possibly add Strings aList. You are trying to assign a list of objects that are guaranteed to be Numbers but can be any Number, to a list that only guarantees you to contain objects but that can be any objects. If the compiler allowed this case it would loosen the restriction on which types of objects are allowed to get into the list. This is why you must use the wildcard ?, as such:

ArrayList<? extends Object> alist = new ArrayList<Number>();

To the compiler ArrayList<? extends Object>, means «an ArrayList of some specific type ‘?’ that I don’t know, but which I know extends Object. This ArrayList is guaranteed to contain only elements of this unknown ‘?’ type, and therefore contains only objects». In this case the compiler will however not allow you to do alist.add(2). Why is that the case, because the compiler doesn’t know the type of the elements of the list, and can’t guarantee that you are allowed to insert Integer objects into it.

You are right in thinking that D<? extends Object> is a supertype of D<? extends C>. However, List<D<? extends Object>> is not a subtype of List<D<? extends C>>, you should be using List<? extends D<? extends C>>.

Your case is basically equivalent to

ArrayList<D<? extends Object>> alist = new ArrayList<D<? extends C>>();

You have the same problem as above, the list on the right hand side can only contain object of class D whose type Parameter is C, and you are trying to assign it to a list (on the left hand side) can contain objects of class D whose type parameter can be any object.

So if the compiler allowed your code would not be type safe, and the following would fail.

ArrayList<D<? extends Object>> alist = new ArrayList<D<? extends C>>(); //< not type safe
alist.add(new D<Number>); //< oops

In short, what you need for your specific example is the following:

// type parameter of left hand side is ? extends subtype
List<? extends D<? extends Object>> b = Arrays.asList(new D<A>(), new D<B>()); 

// type parameter of left hand side is identical
List<D<? extends C>> b = Arrays.asList(new D<A>(), new D<B>());

// type parameter of left hand side is ? extends subtype
List<? extends D<? extends C>> c = Arrays.asList(new D<A>());

// type parameter of left hand side is identical
List<D<A>> c = Arrays.asList(new D<A>());

Hope this helps.

Содержание

  1. How to Handle the Incompatible Types Error in Java
  2. Introduction to Data Types & Type Conversion
  3. Incompatible Types Error: What, Why & How?
  4. Incompatible Types Error Examples
  5. Explicit type casting
  6. Русские Блоги
  7. 20 распространенных ошибок Java и как их избежать
  8. Ошибка компилятора
  9. 1. “… Expected”
  10. 2. “Unclosed String Literal”
  11. 3. “Illegal Start of an Expression”
  12. 4. “Cannot Find Symbol”
  13. 5. “Public Class XXX Should Be in File”
  14. 6. “Incompatible Types”
  15. 7. “Invalid Method Declaration; Return Type Required”
  16. 8. “Method in Class Cannot Be Applied to Given Types”
  17. 9. “Missing Return Statement”
  18. 10. “Possible Loss of Precision”
  19. 11. “Reached End of File While Parsing”
  20. 12. “Unreachable Statement”
  21. 13. “Variable Might Not Have Been Initialized”
  22. 14. “Operator … Cannot be Applied to ”
  23. 15. “Inconvertible Types”
  24. 16. “Missing Return Value”
  25. 17. “Cannot Return a Value From Method Whose Result Type Is Void”
  26. 18. “Non-Static Variable … Cannot Be Referenced From a Static Context”
  27. 19. “Non-Static Method … Cannot Be Referenced From a Static Context”
  28. 20. “(array) Not Initialized”
  29. Продолжение следует
  30. Интеллектуальная рекомендация
  31. IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS
  32. Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis
  33. 1086 Не скажу (15 баллов)
  34. Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных
  35. PureMVC Learning (Tucao) Примечания

How to Handle the Incompatible Types Error in Java

Table of Contents

Introduction to Data Types & Type Conversion

Variables are memory containers used to store information. In Java, every variable has a data type and stores a value of that type. Data types, or types for short, are divided into two categories: primitive and non-primitive. There are eight primitive types in Java: byte , short , int , long , float , double , boolean and char . These built-in types describe variables that store single values of a predefined format and size. Non-primitive types, also known as reference types, hold references to objects stored somewhere in memory. The number of reference types is unlimited, as they are user-defined. A few reference types are already baked into the language and include String , as well as wrapper classes for all primitive types, like Integer for int and Boolean for boolean . All reference types are subclasses of java.lang.Object [1].

In programming, it is commonplace to convert certain data types to others in order to allow for the storing, processing, and exchanging of data between different modules, components, libraries, APIs, etc. Java is a statically typed language, and as such has certain rules and constraints in regard to working with types. While it is possible to convert to and from certain types with relative ease, like converting a char to an int and vice versa with type casting [2], it is not very straightforward to convert between other types, such as between certain primitive and reference types, like converting a String to an int , or one user-defined type to another. In fact, many of these cases would be indicative of a logical error and require careful consideration as to what is being converted and how, or whether the conversion is warranted in the first place. Aside from type casting, another common mechanism for performing type conversion is parsing [3], and Java has some predefined methods for performing this operation on built-in types.

Incompatible Types Error: What, Why & How?

The incompatible types error indicates a situation where there is some expression that yields a value of a certain data type different from the one expected. This error implies that the Java compiler is unable to resolve a value assigned to a variable or returned by a method, because its type is incompatible with the one declared on the variable or method in question. Incompatible, in this context, means that the source type is both different from and unconvertible (by means of automatic type casting) to the declared type.

This might seem like a syntax error, but it is a logical error discovered in the semantic phase of compilation. The error message generated by the compiler indicates the line and the position where the type mismatch has occurred and specifies the incompatible types it has detected. This error is a generalization of the method X in class Y cannot be applied to given types and the constructor X in class Y cannot be applied to given types errors discussed in [4].

The incompatible types error most often occurs when manual or explicit conversion between types is required, but it can also happen by accident when using an incorrect API, usually involving the use of an incorrect reference type or the invocation of an incorrect method with an identical or similar name.

Incompatible Types Error Examples

Explicit type casting

Assigning a value of one primitive type to another can happen in one of two directions. Either from a type of a smaller size to one of a larger size (upcasting), or from a larger-sized type to a smaller-sized type (downcasting). In the case of the former, the data will take up more space but will be intact as the larger type can accommodate any value of the smaller type. So the conversion here is done automatically. However, converting from a larger-sized type to a smaller one necessitates explicit casting because some data may be lost in the process.

Fig. 1(a) shows how attempting to assign the values of the two double variables a and b to the int variables x and y results in the incompatible types error at compile-time. Prefixing the variables on the right-hand side of the assignment with the int data type in parenthesis (lines 10 & 11 in Fig. 1(b)) fixes the issue. Note how both variables lost their decimal part as a result of the conversion, but only one kept its original value—this is exactly why the error message reads possible lossy conversion from double to int and why the incompatible types error is raised in this scenario. By capturing this error, the compiler prevents accidental loss of data and forces the programmer to be deliberate about the conversion. The same principle applies to downcasting reference types, although the process is slightly different as polymorphism gets involved [5].

Источник

Русские Блоги

20 распространенных ошибок Java и как их избежать

оригинал:50 Common Java Errors and How to Avoid Them (Part 1)
Автор:Angela Stringfellow
перевод: Гусь напуган

Примечание переводчика: в этой статье представлены 20 распространенных ошибок компилятора Java. Каждая ошибка включает фрагменты кода, описания проблем и предоставляет ссылки по теме, которые помогут вам быстро понять и решить эти проблемы. Ниже приводится перевод.

При разработке программного обеспечения Java вы можете столкнуться со многими типами ошибок, но большинства из них можно избежать. Мы тщательно отобрали 20 наиболее распространенных ошибок программного обеспечения Java, включая примеры кода и руководства, которые помогут вам решить некоторые распространенные проблемы с кодированием.

Чтобы получить дополнительные советы и рекомендации по написанию программ на Java, вы можете загрузить наш «Comprehensive Java Developer’s Guide«Эта книга содержит все, что вам нужно, от всевозможных инструментов до лучших веб-сайтов и блогов, каналов YouTube, влиятельных лиц в Twitter, групп в LinkedIn, подкастов, мероприятий, которые необходимо посетить, и многого другого.

Если вы используете .NET, прочтите нашРуководство по 50 наиболее распространенным программным ошибкам .NETЧтобы избежать этих ошибок. Но если ваша текущая проблема связана с Java, прочтите следующую статью, чтобы понять наиболее распространенные проблемы и способы их решения.

Ошибка компилятора

Сообщения об ошибках компилятора создаются, когда компилятор выполняет код Java. Важно, что компилятор может выдавать несколько сообщений об ошибках для одной ошибки. Так что исправьте ошибку и перекомпилируйте, что может решить многие проблемы.

1. “… Expected”

Эта ошибка возникает, когда в коде чего-то не хватает. Обычно это происходит из-за отсутствия точки с запятой или закрывающей скобки.

Обычно это сообщение об ошибке не указывает точное местонахождение проблемы. Чтобы найти проблему, вам необходимо:

  • Убедитесь, что все открывающие скобки имеют соответствующие закрывающие скобки.
  • Посмотрите на код перед строкой, обозначенной ошибкой. Эта ошибка обычно обнаруживается компилятором в более позднем коде.
  • Иногда некоторые символы (например, открывающая скобка) не должны быть первыми в коде Java.

2. “Unclosed String Literal”

Если в конце строки отсутствует кавычка, создается сообщение об ошибке «Незамкнутый строковый литерал», и это сообщение отображается в строке, где произошла ошибка.

Обычно эта ошибка возникает в следующих ситуациях:

  • Строка не заканчивается кавычками. Это легко изменить, просто заключите строку в указанные кавычки.
  • Строка превышает одну строку. Длинную строку можно разделить на несколько коротких строк и соединить знаком плюс («+»).
  • Кавычки, являющиеся частью строки, не экранируются обратной косой чертой («»).

3. “Illegal Start of an Expression”

Есть много причин для ошибки «Незаконное начало выражения». Это стало одним из наименее полезных сообщений об ошибках. Некоторые разработчики думают, что это вызвано плохим запахом кода.

Обычно выражение создается для генерации нового значения или присвоения значений другим переменным. Компилятор ожидает найти выражение, но посколькуГрамматика не оправдывает ожиданийВыражение не найдено. Эту ошибку можно найти в следующем коде.

4. “Cannot Find Symbol”

Это очень распространенная проблема, потому что все идентификаторы в Java должны быть объявлены до их использования. Эта ошибка возникает из-за того, что компилятор не понимает значения идентификатора при компиляции кода.

Сообщение об ошибке «Не удается найти символ» может иметь множество причин:

  • Написание объявления идентификатора может не соответствовать написанию, используемому в коде.
  • Переменная никогда не объявлялась.
  • Переменная не объявлена ​​в той же области видимости.
  • Никакие классы не импортируются.

5. “Public Class XXX Should Be in File”

Если класс XXX и имя файла программы Java не совпадают, будет сгенерировано сообщение об ошибке «Открытый класс XXX должен быть в файле». Только когда имя класса и имя файла Java совпадают, код может быть скомпилирован.

Чтобы решить эту проблему, вы можете:

  • Назовите класс и файл с тем же именем.
  • Убедитесь, что два имени всегда совпадают.

6. “Incompatible Types”

«Несовместимые типы» — это логические ошибки, которые возникают, когда операторы присваивания пытаются сопоставить типы переменных и выражений. Обычно эта ошибка возникает при присвоении строки целому числу и наоборот. Это не синтаксическая ошибка Java.

Когда компилятор выдает сообщение «несовместимые типы», решить эту проблему действительно непросто:

  • Используйте функции преобразования типов.
  • Разработчикам может потребоваться изменить исходные функции кода.

7. “Invalid Method Declaration; Return Type Required”

Это сообщение об ошибке означает, что тип возвращаемого значения метода не объявлен явно в объявлении метода.

Есть несколько ситуаций, которые вызывают ошибку «недопустимое объявление метода; требуется тип возвращаемого значения»:

  • Забыл объявить тип.
  • Если метод не имеет возвращаемого значения, вам необходимо указать «void» в качестве возвращаемого типа в объявлении метода.
  • Конструктору не нужно объявлять тип. Однако, если в имени конструктора есть ошибка, компилятор будет рассматривать конструктор как метод без указанного типа.

8. “Method in Class Cannot Be Applied to Given Types”

Это сообщение об ошибке более полезно, оно означает, что метод был вызван с неправильными параметрами.

При вызове метода вы должны передать те параметры, которые определены в его объявлении. Пожалуйста, проверьте объявление метода и вызов метода, чтобы убедиться, что они совпадают.

9. “Missing Return Statement”

Когда в методе отсутствует оператор возврата, выдается сообщение об ошибке «Отсутствует оператор возврата». Метод с возвращаемым значением (тип, не являющийся недействительным) должен иметь оператор, который возвращает значение, чтобы значение можно было вызвать вне метода.

Есть несколько причин, по которым компилятор выдает сообщение «отсутствует оператор возврата»:

  • Оператор возврата был опущен по ошибке.
  • Метод не возвращает никакого значения, но тип не объявлен как недействительный в объявлении метода.

10. “Possible Loss of Precision”

Когда информация, присвоенная переменной, превышает верхний предел, который может нести переменная, выдается ошибка «Возможная потеря точности». Как только это произойдет, часть информации будет отброшена. Если это не проблема, переменную следует явно объявить в коде как новый тип.

Ошибка «возможная потеря точности» обычно возникает в следующих ситуациях:

  • Попробуйте присвоить переменной целочисленного типа действительное число.
  • Попробуйте присвоить данные типа double переменной целочисленного типа.

Основные типы данных в JavaОбъясняет характеристики различных типов данных.

11. “Reached End of File While Parsing”

Это сообщение об ошибке обычно появляется, когда в программе отсутствует закрывающая фигурная скобка («>»). Иногда эту ошибку можно быстро исправить, добавив закрывающую скобку в конце кода.

Приведенный выше код приведет к следующей ошибке:

Инструменты кодирования и правильные отступы кода могут упростить поиск этих несоответствующих фигурных скобок.

12. “Unreachable Statement”

Когда оператор появляется в месте, где он не может быть выполнен, выдается ошибка «Недоступный оператор». Обычно это делается после оператора break или return.

Обычно эту ошибку можно исправить, просто переместив оператор return. Прочтите эту статью:Как исправить ошибку «Недостижимый отчет»。

13. “Variable Might Not Have Been Initialized”

Если локальная переменная, объявленная в методе, не инициализирована, возникнет такая ошибка. Такая ошибка возникает, если вы включаете переменную без начального значения в оператор if.

14. “Operator … Cannot be Applied to ”

Эта проблема возникает, когда оператор действует с типом, который не входит в область его определения.

Эта ошибка часто возникает, когда код Java пытается использовать строковые типы в вычислениях (вычитание, умножение, сравнение размеров и т. Д.). Чтобы решить эту проблему, вам необходимо преобразовать строку в целое число или число с плавающей запятой.

15. “Inconvertible Types”

Когда код Java пытается выполнить недопустимое преобразование, возникает ошибка «Неконвертируемые типы».

Например, логические типы нельзя преобразовать в целые числа.

16. “Missing Return Value”

Если оператор возврата содержит неверный тип, вы получите сообщение «Отсутствует возвращаемое значение». Например, посмотрите на следующий код:

Возвращается следующая ошибка:

Обычно эта ошибка возникает из-за того, что оператор return ничего не возвращает.

17. “Cannot Return a Value From Method Whose Result Type Is Void”

Эта ошибка Java возникает, когда метод void пытается вернуть какое-либо значение, например, в следующем коде:

Обычно эту проблему может решить изменение типа возвращаемого значения метода, чтобы он соответствовал типу в операторе возврата. Например, следующий void можно изменить на int:

18. “Non-Static Variable … Cannot Be Referenced From a Static Context”

Эта ошибка возникает, когда компилятор пытается получить доступ к нестатической переменной в статическом методе:

Чтобы устранить ошибку «Нестатическая переменная… На нее нельзя ссылаться из статического контекста», можно сделать две вещи:

  • Вы можете объявить переменные статическими.
  • Вы можете создавать экземпляры нестатических объектов в статических методах.

19. “Non-Static Method … Cannot Be Referenced From a Static Context”

Эта проблема возникает, когда код Java пытается вызвать нестатический метод в статическом классе. Например, такой код:

Вызовет эту ошибку:

Чтобы вызвать нестатический метод в статическом методе, необходимо объявить экземпляр класса вызываемого нестатического метода.

20. “(array) Not Initialized”

Если массив был объявлен, но не инициализирован, вы получите сообщение об ошибке типа «(массив) не инициализирован». Длина массива фиксирована, поэтому каждый массив необходимо инициализировать требуемой длиной.

Следующий код правильный:

это тоже нормально:

Продолжение следует

Сегодня мы обсуждали ошибки компилятора, в следующий раз мы обсудим различные исключения времени выполнения, которые могут возникнуть. Как и структура этой статьи, в следующий раз она будет содержать фрагменты кода, пояснения и ссылки по теме, которые помогут вам исправить код как можно скорее.

Интеллектуальная рекомендация

IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS

Используйте iview, чтобы сделать небольшой инструмент. Чтобы не затронуть другие платформы, загрузите JS и CSS CDN на локальные ссылки. В результате значок шрифта не может быть загружен. Просмо.

Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis

1 Обзор Серверная программа, которая обычно запускалась раньше, открылась сегодня, и неожиданно появилась эта ошибка. Интуитивно понятно, что не хватает связанных с Spring пакетов, но после удаления п.

1086 Не скажу (15 баллов)

При выполнении домашнего задания друг, сидящий рядом с ним, спросил вас: «Сколько будет пять умножить на семь?» Вы должны вежливо улыбнуться и сказать ему: «Пятьдесят три». Это.

Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных

В конкурсе Algorith Algorith Algorith Algorith Algorith 2019 года используется многофункциональная уборка номера ускорения. Будет использовать панды. Но сама панда, кажется, не имеет механизма для мно.

PureMVC Learning (Tucao) Примечания

Справочная статья:Введение подробного PrueMVC Использованная литература:Дело UnityPureMvc Основная цель этой статьи состоит в том, чтобы организовать соответствующие ресурсы о PureMVC. Что касается Pu.

Источник

Опытные разработчики должны знать эти 3 трюка, чтобы устранить распространенные проблемы с дженериками

Деловое фото создано yanalya — www.freepik.com

Деловое фото создано yanalya — www.freepik.com

Вы знаете о системе PECS? Знаете ли вы о типах пересечений? Знаете ли вы, где используется создание дженерик массивов?

Большинство разработчиков Java используют дженерики без глубоких знаний. А вы должны знать ответы на эти вопросы. Если вы будете знать их, вы устраните многие проблемы, связанные с generics.

Давайте ответим на эти вопросы.

1. Вы можете использовать extends с интерфейсами

Согласно этим документам, вы можете использовать interfaceType после ключевого слова extends. Вы можете соединить их в цепочку, чтобы сформировать типы пересечения. Это может привести к странным ошибкам во время выполнения.

Давайте рассмотрим следующий вопрос на Stack Overflow.

Код в вопросе следующий:

<X extends CharSequence> X getCharSequence() {
    return (X) "hello";
}
<X extends String> X getString() {
    return (X) "hello";
}

Если мы запустим его в jShell 11, то получим следующий результат:

jshell> <X extends CharSequence> X getCharSequence() {
   ...>     return (X) "hello";
   ...> }
   ...> 
   ...> <X extends String> X getString() {
   ...>     return (X) "hello";
   ...> }

|  Warning:
|  unchecked cast
|    required: X
|    found:    java.lang.String
|      return (X) "hello";
|                 ^-----^
|  created method getCharSequence()
|  Warning:
|  unchecked cast
|    required: X
|    found:    java.lang.String
|      return (X) "hello";
|                 ^-----^
|  created method getString()

jshell> Integer x = getCharSequence();
   ...> 

|  Exception java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
|        at (#3:1)

jshell> Integer y = getString();
   ...> 

|  Error:
|  incompatible types: inference variable X has incompatible upper bounds java.lang.Integer,java.lang.String
|  Integer y = getString();

В обоих примерах мы получаем предупреждение о непроверенном приведении. Это потому, что в обоих примерах мы возвращаем String, а не X. Тем не менее, оба метода создаются.

Когда мы загружаем getCharSequence, мы получаем не ошибку времени компиляции, а ошибку времени выполнения. Для getString мы получаем ошибку времени компиляции.

Почему так происходит?

Для первого метода Java определяет тип пересечения. В данном случае это Integer & CharSequence а Integer может быть подклассом CharSequence. Вот почему с точки зрения компиляции это корректное присваивание, несмотря на то, что Integer является final class.

Ошибка во время выполнения возникает, поскольку мы возвращаем значение String, не соответствующее типу Integer & CharSequence. Поскольку проверки во время выполнения нет, мы получаем исключение ClassCastException.

Почему во втором примере возникает ошибка времени компиляции?

String — это final класс, и вы не можете расширить его как String. Он не относится к типу CharSequence, который является интерфейсом. Ему невозможно иметь тип пересечения Integer & String, и это известно во время компиляции.

2. Вы можете создавать типобезопасные generic массивы

Один из способов создания generic массивов заключается в следующем:

public <T> T[] array(T... values) {
    return values;
}

Но даже в этом случае выдается следующее предупреждение:

jshell> public <T> T[] array(T... values) {
   ...>     return values;
   ...> }

|  Warning:
|  Possible heap pollution from parameterized vararg type T
|  public <T> T[] array(T... values) {
|                       ^---------^
|  created method array(T...)

Так что же означает загрязнение кучи (heap pollution)?

Переменная содержит ссылку на неправильный тип. Или, другими словами, тип переменной не является нужным типом.

Heap pollution (загрязнение кучи) происходит, когда переменная параметризованного типа ссылается на объект, не относящийся к этому параметризованному типу. Такая ситуация возникает, если программа выполнила какую-то операцию, которая вызывает непроверенное предупреждение во время компиляции. Непроверенное предупреждение выдается, если либо во время компиляции (в рамках правил проверки типов во время компиляции), либо во время выполнения невозможно проверить корректность операции с параметризованным типом (например, приведение или вызов метода). Например, загрязнение кучи происходит при смешивании необработанных и параметризованных типов или при выполнении непроверенных приведений типов — source

Вы можете подавить эти предупреждения. И это используется в одном методе, который мы все используем: Collections#emptyList()

Так почему же этот сценарий хорош? 

Вы можете быть уверены, что даже при стирании типов  (type erasure) будет создан пустой список нужного типа. Вы можете быть спокойны, потому что это пустой список, поэтому подойдет любой тип.

Таким образом, проблема заключается в безопасности типов, и для ее решения вам необходимо предоставить нужный тип. Вы можете сделать это с помощью функции генератора. Она используется в функции toArray.

А вот наша собственная реализация.

jshell> class Generic<E> {
   ...>    
   ...>     private E[] array;
   ...> 
   ...>     GenericSet(IntFunction<E[]> generator) {
   ...>         this.array = generator.apply(0);
   ...>     }
   ...> 
   ...>     public static void main(String[] args) {
   ...>         Generic<String> ofString =
   ...>             new Generic<>(String[]::new);
   ...>         Generic<Double> ofDouble =
   ...>             new Generic<>(Double[]::new);
   ...>     }
   ...> }

3. Producer Extends, Consumer Super

Я полагаю, вы встречали и extends и super в Java коде с generic.

Так почему вы должны использовать extends? Каковы ограничения extends? И какова цель super?

Мнемоника PECS взята из выступления Джошуа на эту тему.

PECS означает:

  • Producer Extends — если вам нужен List, чтобы выдавать значения T (вы хотите читатьT из списка), вам нужно объявить его с помощью ? extends T, например, List<? extends Integer>. Но вы не можете добавить значение в этот список.

  • Consumer Super — если вам нужен List для получения значений типа T (вы хотите записывать значения типа T в список), вам нужно объявить его с помощью ? super T, например, List<? super Integer>. Но нет никаких гарантий, какой тип объекта вы можете прочитать из этого списка.

Вы не можете добавить в список производителей, и вы не можете прочитать из списка потребителей.

Вот доказательства:

jshell> List<? extends Number> foo3 = List.of(1.23);
foo3 ==> [1.23]

jshell> foo3.get(0)
$27 ==> 1.23

jshell> foo3.add(1.34)

|  Error:
|  incompatible types: double cannot be converted to capture#10 of ? extends java.lang.Number
|  foo3.add(1.34)
|           ^--^
jshell> List<? super Number> foo3 = new ArrayList<Number>();
foo3 ==> []
  
jshell> foo3.add(1)
$32 ==> true
  
jshell> foo3
foo3 ==> [1]
  
jshell> foo3.get(0)
$34 ==> 1
 

jshell> Number r = foo3.get(0)

|  Error:
|  incompatible types: capture#11 of ? super java.lang.Number cannot be converted to java.lang.Number
|  Number r = foo3.get(0);
|             ^---------^

Почему это происходит?

Нет гарантии с обеих сторон, так как происходит стирание типов.

Когда вы используете extends, у вас есть гарантия того, что вы можете читать. Это тип после wildcard  знака extends или его подклассов. И у вас нет гарантии того, что вы можете добавить, так как тип стирается во время выполнения.

Когда вы используете super, у вас есть гарантия того, какой тип вы можете добавить. Это тип после wildcard super или его подклассов. И у вас нет гарантии того, что вы можете прочитать, так как тип стирается во время выполнения.

Еще одно хорошее и простое объяснение (source):

Collections#copy — хороший пример этого принципа.

dst будет потреблять значения типа T, поэтому wildcard super гарантирует это. src будет производить значения, поэтому extends будет гарантировать это. Но даже в этом случае нет гарантии типа при добавлении в src или чтении из dst.

Что, если вы заранее знаете типы и хотите использовать wildcard?

Вы можете немного обмануть компилятор. Кроме того, вы получите предупреждение, которое можно подавить с помощью аннотации компилятора. Но поскольку вы уверены в типах, которые вы предоставляете, это будет работать для вашего сценария.

Допустим, мы используем super (Consumer из PECS) для foo3. С помощью явного приведения к List<Number> вы можете гарантировать какой тип вы читаете из foo3Unchecked. В данном случае мы гарантируем, что это Number что чтение Integer приведет к ошибке преобразования.

Какие особенности дженериков вы знаете? Дайте мне знать в разделе комментариев.

1. Overview

In this quick tutorial, we’ll discuss the concept of lossy conversion in Java and the reason behind it.

At the same time, we’ll explore some handy conversion techniques to avoid this error.

Lossy conversion is simply the loss of information while handling data.

In Java, it corresponds to the possibility of losing the value or precision of a variable while converting one type to another.

When we try to assign a variable of large-sized type to a smaller sized type, Java will generate an error, incompatible types: possible lossy conversion, while compiling the code.

For example, let’s try to assign a long to an int:

long longNum = 10;
int intNum = longNum;

Java will emit an error while compiling this code:

incompatible types: possible lossy conversion from long to int

Here, Java will find long and int incompatible and result in lossy conversion error. Because there can be long values outside the int range -2,147,483,648 to 2,147,483,647.

Similarly, let’s try to assign a float to a long:

float floatNum = 10.12f;
long longNum = floatNum;
incompatible types: possible lossy conversion from float to long

As float can have decimal values that don’t have corresponding long value. Therefore, we’ll receive the same error.

Similarly, assigning a double number to an int will cause the same error:

double doubleNum = 1.2;
int intNum = doubleNum;
incompatible types: possible lossy conversion from double to int

The double values can be too large or too small for an int and decimal values will get lost in the conversion. Hence, it is a potential lossy conversion.

Also, we can run into this error while performing a simple calculation:

int fahrenheit = 100;
int celcius = (fahrenheit - 32) * 5.0 / 9.0;

When a double multiply with an int, we get the result in a double. Consequently, it is also a potential lossy conversion.

Therefore, the incompatible types in lossy conversion can either have different sizes or types (integers or decimals).

3. Primitive Data Types

In Java, there are many primitive data types available with their corresponding wrapper classes.

Next, let’s compile a handy list of all possible lossy conversions in Java:

  • short to byte or char
  • char to byte or short
  • int to byte, short or char
  • long to byte, short, char or int
  • float to byte, short, char, int or long
  • double to byte, short, char, int, long or float

Note that though short and char have the same size. Still, the conversion from short to char is lossy because char is an unsigned data type.

4. Conversion Techniques

4.1. Converting Between Primitive Types

The easy way of converting primitives to avoid lossy conversion is through downcasting; in other words, casting the larger-sized type to a smaller-sized type. Hence, it is also called narrowing primitive conversion.

For instance, let’s convert a long number to a short using downcasting:

long longNum = 24;
short shortNum = (short) longNum;
assertEquals(24, shortNum);

Similarly, let’s convert a double to an int:

double doubleNum = 15.6;
int integerNum = (int) doubleNum;
assertEquals(15, integerNum);

However, we should note that converting large-sized type with values too large or too small to smaller-sized type through downcasting can result in unexpected values.

Let’s convert long values outside the range of short:

long largeLongNum = 32768; 
short minShortNum = (short) largeLongNum;
assertEquals(-32768, minShortNum);

long smallLongNum = -32769;
short maxShortNum = (short) smallLongNum;
assertEquals(32767, maxShortNum);

If we carefully analyze the conversion, we’ll see that these are not the expected values.

In other words, when Java hits the highest value of a small-sized type while converting from large-sized type, the next number is the lowest value of the small-sized type and vice-versa.

Let’s understand this through examples. When largeLongNum with the value of 32768 is converted to short, the value of shortNum1 is -32768. Because the max value of short is 32767, therefore, Java goes for the next min value of the short.

Similarly, when smallLongNum is converted to short. The value of shortNum2 is 32767 as Java goes for the next max value of the short.

Also, let’s see what happens when we convert the max and min values of a long to an int:

long maxLong = Long.MAX_VALUE; 
int minInt = (int) maxLong;
assertEquals(-1, minInt);

long minLong = Long.MIN_VALUE;
int maxInt = (int) minLong;
assertEquals(0, maxInt);

4.2. Converting Between Wrapper Objects and Primitive Types

To directly convert a wrapper object to a primitive, we can use various methods in wrapper classes such as intValue(), shortValue() and longValue(). This is called unboxing.

For instance, let’s convert a Float object to a long:

Float floatNum = 17.564f;
long longNum = floatNum.longValue();
assertEquals(17, longNum);

Also, if we look at the implementation of longValue or similar methods, we’ll find the use of narrowing primitive conversion:

public long longValue() {
    return (long) value;
}

However, at times, narrowing primitive conversion should be avoided to save valuable information:

Double doubleNum = 15.9999;
long longNum = doubleNum.longValue();
assertEquals(15, longNum);

After conversion, the value of longNum will be 15. However, the doubleNum is 15.9999, which is very close to 16.

Instead, we can use Math.round() for conversion to the closest integer:

Double doubleNum = 15.9999;
long longNum = Math.round(doubleNum);

assertEquals(16, longNum);

4.3. Converting Between Wrapper Objects

For this, let’s use the already discussed conversion techniques.

First, we’ll convert wrapper object to a primitive value, downcast it and convert it to another wrapper object. In other words, we’ll perform unboxing, downcasting, and boxing techniques.

For example, let’s convert a Double object to an Integer object:

Double doubleNum = 10.3;
double dbl = doubleNum.doubleValue(); // unboxing
int intgr = (int) dbl; // downcasting
Integer intNum = Integer.valueOf(intgr);
assertEquals(Integer.valueOf(10), intNum);

Lastly, we’re using Integer.valueOf() to convert the primitive type int to an Integer object. This type of conversion is called boxing.

5. Conclusion

In this article, we’ve explored the concept of lossy conversion in Java with the help of a number of examples. In addition, we’ve compiled a handy list of all possible lossy conversions as well.

Along the way, we’ve identified narrowing primitive conversion as an easy technique to convert primitive numbers and avoid the lossy conversion error.

At the same time, we’ve also explored additional handy techniques for numeric conversions in Java.

The code implementations for this article can be found over on GitHub.

In this post I will be sharing how to fix incompatible types: int cannot be converted to int[] error. This error occurs at compile-time. As always, first, we will produce the error incompatible types: int cannot be converted to int[] error, before moving on to the solution.

Read Also: int to Integer in Java

[Fixed] incompatible types: int cannot be converted to int[] error

Example 1: Producing the error by assigning an int to a variable whose type is int[]

We can easily produce this error by assigning an int to a variable whose type is int[] as shown below:

public class IntCanNotBeConvertedToIntArray {
  static int[] array;
  static int count;

  public static void printArray(int size) {
      

array = size;

count = size; for (int i=0; i<count ; i++) { array[i] = i; System.out.print(array[i]+" "); } } public static void main(String args[]) { printArray(13); } }

Output:
IntCanNotBeConvertedToIntArray.java:7: error: incompatible types: int cannot be converted to int[]
            array = size;
                         ^
1 error

Explanation:

The cause of this error is by assigning an int to a variable whose type is int[]. In the above code, we need to initialize the array variable to an array, not to an integer. We can use a new keyword to initialize the array.

Solution:

In Java, we need to initialize the array variable not to an integer but an array. We can use the new keyword to solve this issue as shown below:

public class IntCanNotBeConvertedToIntArray {
  static int[] array;
  static int count;

  public static void printArray(int size) {
      

array = new int[size];

count = size; for (int i=0; i<count ; i++) { array[i] = i; System.out.print(array[i]+" "); } } public static void main(String args[]) { printArray(13); } }

Output:
0 1 2 3 4 5 6 7 8 9 10 11 12

Example 2: Producing the error by returning an int instead of int[] in the method

We can easily produce this error by returning an int instead of int[] as shown below:

public class IntCanNotBeConvertedToIntArray2 {
  static int[] array;

  public static int[] displayArray(int size) {
      array = new int[size];
      for (int i=0; i < size ; i++) {
          System.out.print(array[i]+" ");
      }    

return size;

} public static void main(String args[]) { displayArray(3); } }

Output:
IntCanNotBeConvertedToIntArray2.java:9: error: incompatible types: int cannot be converted to int[]
            return size;
                        ^
1 error

Explanation:

The cause of this error is by returning an int instead of int[] in the displayArray method.

Solution:

In the displayArray method, we need to return an int[] instead of int. Just replace size which is an int with an int[] array in the return type of the displayArray method as shown below:

public class IntCanNotBeConvertedToIntArray2 {
  static int[] array;

  public static int[] displayArray(int size) {
      array = new int[size];
      for (int i=0; i < size ; i++) {
          System.out.print(array[i]+" ");
      }     

return array;

} public static void main(String args[]) { displayArray(3); } }

Output:
0 0 0

That’s all for today. Please mention in the comments in case you are still facing the error incompatible types: int cannot be converted to int[] in Java.

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

Java error incompatible types

  
  

Java Error incompatible types occurred when a compiler found a variable and
expression whose data type is not compatible to perform an operation on them.

Understand with an Example

In this Tutorial we want to describe you a code that help you in
understanding the java error incompatible type. For this we have a class name
Incompatobletype.Inside the main method we declare a variable name roll num 
and sec int and char  data type. Checklist condition is used to evaluate
the expression. The assignment operator = is used to show you an incompatible
type error in java rather than using = = in assignment operator. The Java
Compiler show an error in the assignment operator printed by System.out.println.

Incompatitabletype.java



public class Icompatobletype {

  public static void main(String[] args) {

  int rollnum = 76;
  char sec;
  if (rollnum = 90) {
  sec = 'A';
  else {
  sec = 'B';
  }
  System.out.println("Section with this rollno is:  = " + sec);
  }
}

Output

Compiling source file to /home/girish/NetBeansProjects/errors/build/classes
/home/girish/NetBeansProjects/errors/src/Icompatobletype.java:8: incompatible types
found : int
required: boolean
  if (rollnum = 90) {
error
BUILD FAILED (total time: seconds)

To resolve this error give if (rollnum = =90)instead of if (rollnum = 90)

Download code

оригинал:50 Common Java Errors and How to Avoid Them (Part 1)
Автор:Angela Stringfellow
перевод: Гусь напуган

Примечание переводчика: в этой статье представлены 20 распространенных ошибок компилятора Java. Каждая ошибка включает фрагменты кода, описания проблем и предоставляет ссылки по теме, которые помогут вам быстро понять и решить эти проблемы. Ниже приводится перевод.

При разработке программного обеспечения Java вы можете столкнуться со многими типами ошибок, но большинства из них можно избежать. Мы тщательно отобрали 20 наиболее распространенных ошибок программного обеспечения Java, включая примеры кода и руководства, которые помогут вам решить некоторые распространенные проблемы с кодированием.

Чтобы получить дополнительные советы и рекомендации по написанию программ на Java, вы можете загрузить наш «Comprehensive Java Developer’s Guide«Эта книга содержит все, что вам нужно, от всевозможных инструментов до лучших веб-сайтов и блогов, каналов YouTube, влиятельных лиц в Twitter, групп в LinkedIn, подкастов, мероприятий, которые необходимо посетить, и многого другого.

Если вы используете .NET, прочтите нашРуководство по 50 наиболее распространенным программным ошибкам .NETЧтобы избежать этих ошибок. Но если ваша текущая проблема связана с Java, прочтите следующую статью, чтобы понять наиболее распространенные проблемы и способы их решения.

Ошибка компилятора

Сообщения об ошибках компилятора создаются, когда компилятор выполняет код Java. Важно, что компилятор может выдавать несколько сообщений об ошибках для одной ошибки. Так что исправьте ошибку и перекомпилируйте, что может решить многие проблемы.

1. “… Expected”

Эта ошибка возникает, когда в коде чего-то не хватает. Обычно это происходит из-за отсутствия точки с запятой или закрывающей скобки.

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;
}

Обычно это сообщение об ошибке не указывает точное местонахождение проблемы. Чтобы найти проблему, вам необходимо:

  • Убедитесь, что все открывающие скобки имеют соответствующие закрывающие скобки.
  • Посмотрите на код перед строкой, обозначенной ошибкой. Эта ошибка обычно обнаруживается компилятором в более позднем коде.
  • Иногда некоторые символы (например, открывающая скобка) не должны быть первыми в коде Java.

Примеры:Ошибка из-за отсутствия скобок。

2. “Unclosed String Literal”

Если в конце строки отсутствует кавычка, создается сообщение об ошибке «Незамкнутый строковый литерал», и это сообщение отображается в строке, где произошла ошибка.

 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");
    }     
}

Обычно эта ошибка возникает в следующих ситуациях:

  • Строка не заканчивается кавычками. Это легко изменить, просто заключите строку в указанные кавычки.
  • Строка превышает одну строку. Длинную строку можно разделить на несколько коротких строк и соединить знаком плюс («+»).
  • Кавычки, являющиеся частью строки, не экранируются обратной косой чертой («»).

Прочтите эту статью:Сообщение об ошибке незакрытой строки。

3. “Illegal Start of an Expression”

Есть много причин для ошибки «Незаконное начало выражения». Это стало одним из наименее полезных сообщений об ошибках. Некоторые разработчики думают, что это вызвано плохим запахом кода.

Обычно выражение создается для генерации нового значения или присвоения значений другим переменным. Компилятор ожидает найти выражение, но посколькуГрамматика не оправдывает ожиданийВыражение не найдено. Эту ошибку можно найти в следующем коде.

} // добавляем сюда
       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.");
        }
        }
    } // удаляем отсюда
    }

Прочтите эту статью:Как устранить ошибки «неправильное начало выражения»。

4. “Cannot Find Symbol”

Это очень распространенная проблема, потому что все идентификаторы в Java должны быть объявлены до их использования. Эта ошибка возникает из-за того, что компилятор не понимает значения идентификатора при компиляции кода.

cannot-find-symbol-error-screenshot-11495

Сообщение об ошибке «Не удается найти символ» может иметь множество причин:

  • Написание объявления идентификатора может не соответствовать написанию, используемому в коде.
  • Переменная никогда не объявлялась.
  • Переменная не объявлена ​​в той же области видимости.
  • Никакие классы не импортируются.

Прочтите эту статью:Обсуждение ошибки «не удается найти символ»。

5. “Public Class XXX Should Be in File”

Если класс XXX и имя файла программы Java не совпадают, будет сгенерировано сообщение об ошибке «Открытый класс XXX должен быть в файле». Только когда имя класса и имя файла Java совпадают, код может быть скомпилирован.

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);  
    }
  }

Чтобы решить эту проблему, вы можете:

  • Назовите класс и файл с тем же именем.
  • Убедитесь, что два имени всегда совпадают.

Прочтите эту статью:Примеры ошибки «Открытый класс XXX должен быть в файле»。

6. “Incompatible Types”

«Несовместимые типы» — это логические ошибки, которые возникают, когда операторы присваивания пытаются сопоставить типы переменных и выражений. Обычно эта ошибка возникает при присвоении строки целому числу и наоборот. Это не синтаксическая ошибка Java.

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

Когда компилятор выдает сообщение «несовместимые типы», решить эту проблему действительно непросто:

  • Используйте функции преобразования типов.
  • Разработчикам может потребоваться изменить исходные функции кода.

Взгляните на этот пример:Присвоение строки целому числу приведет к ошибке «несовместимые типы».。

7. “Invalid Method Declaration; Return Type Required”

Это сообщение об ошибке означает, что тип возвращаемого значения метода не объявлен явно в объявлении метода.

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

Есть несколько ситуаций, которые вызывают ошибку «недопустимое объявление метода; требуется тип возвращаемого значения»:

  • Забыл объявить тип.
  • Если метод не имеет возвращаемого значения, вам необходимо указать «void» в качестве возвращаемого типа в объявлении метода.
  • Конструктору не нужно объявлять тип. Однако, если в имени конструктора есть ошибка, компилятор будет рассматривать конструктор как метод без указанного типа.

Взгляните на этот пример:Проблема именования конструктора вызывает проблему «недопустимое объявление метода; требуется тип возвращаемого значения».。

8. “Method in Class Cannot Be Applied to Given Types”

Это сообщение об ошибке более полезно, оно означает, что метод был вызван с неправильными параметрами.

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

При вызове метода вы должны передать те параметры, которые определены в его объявлении. Пожалуйста, проверьте объявление метода и вызов метода, чтобы убедиться, что они совпадают.

Это обсуждение иллюстрируетОшибки Java, вызванные несовместимостью объявлений методов и параметров в вызовах методов。

9. “Missing Return Statement”

Когда в методе отсутствует оператор возврата, выдается сообщение об ошибке «Отсутствует оператор возврата». Метод с возвращаемым значением (тип, не являющийся недействительным) должен иметь оператор, который возвращает значение, чтобы значение можно было вызвать вне метода.

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!");
    }
}

Есть несколько причин, по которым компилятор выдает сообщение «отсутствует оператор возврата»:

  • Оператор возврата был опущен по ошибке.
  • Метод не возвращает никакого значения, но тип не объявлен как недействительный в объявлении метода.

пожалуйста, проверьтеКак устранить ошибку «отсутствует отчет о возврате»Это пример.

10. “Possible Loss of Precision”

Когда информация, присвоенная переменной, превышает верхний предел, который может нести переменная, выдается ошибка «Возможная потеря точности». Как только это произойдет, часть информации будет отброшена. Если это не проблема, переменную следует явно объявить в коде как новый тип.

possible-loss-of-precision-error-11501

Ошибка «возможная потеря точности» обычно возникает в следующих ситуациях:

  • Попробуйте присвоить переменной целочисленного типа действительное число.
  • Попробуйте присвоить данные типа double переменной целочисленного типа.

Основные типы данных в JavaОбъясняет характеристики различных типов данных.

11. “Reached End of File While Parsing”

Это сообщение об ошибке обычно появляется, когда в программе отсутствует закрывающая фигурная скобка («}»). Иногда эту ошибку можно быстро исправить, добавив закрывающую скобку в конце кода.

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
   });
}

Приведенный выше код приведет к следующей ошибке:

java:11: reached end of file while parsing }

Инструменты кодирования и правильные отступы кода могут упростить поиск этих несоответствующих фигурных скобок.

Прочтите эту статью:Отсутствие фигурных скобок вызовет сообщение об ошибке «достигнут конец файла при синтаксическом анализе».。

12. “Unreachable Statement”

Когда оператор появляется в месте, где он не может быть выполнен, выдается ошибка «Недоступный оператор». Обычно это делается после оператора break или return.

for(;;){
   break;
   ... // unreachable statement
}
int i=1;
if(i==1)
  ...
else
  ... // dead code

Обычно эту ошибку можно исправить, просто переместив оператор return. Прочтите эту статью:Как исправить ошибку «Недостижимый отчет»。

13. “Variable Might Not Have Been Initialized”

Если локальная переменная, объявленная в методе, не инициализирована, возникнет такая ошибка. Такая ошибка возникает, если вы включаете переменную без начального значения в оператор if.

int x;
if (condition) {
    x = 5;
}
System.out.println(x); // x не может быть инициализирован

Прочтите эту статью:Как избежать появления ошибки «Возможно, переменная не была инициализирована»。

14. “Operator … Cannot be Applied to ”

Эта проблема возникает, когда оператор действует с типом, который не входит в область его определения.

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

Эта ошибка часто возникает, когда код Java пытается использовать строковые типы в вычислениях (вычитание, умножение, сравнение размеров и т. Д.). Чтобы решить эту проблему, вам необходимо преобразовать строку в целое число или число с плавающей запятой.

Прочтите эту статью:Почему нечисловые типы вызывают ошибки программного обеспечения Java。

15. “Inconvertible Types”

Когда код Java пытается выполнить недопустимое преобразование, возникает ошибка «Неконвертируемые типы».

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;
                                                     ^

Например, логические типы нельзя преобразовать в целые числа.

Прочтите эту статью:Как преобразовывать неконвертируемые типы в программном обеспечении Java。

16. “Missing Return Value”

Если оператор возврата содержит неверный тип, вы получите сообщение «Отсутствует возвращаемое значение». Например, посмотрите на следующий код:

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;
    }
}

Возвращается следующая ошибка:

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

Обычно эта ошибка возникает из-за того, что оператор return ничего не возвращает.

Прочтите эту статью:Как избежать ошибки «Отсутствует возвращаемое значение»。

17. “Cannot Return a Value From Method Whose Result Type Is Void”

Эта ошибка Java возникает, когда метод void пытается вернуть какое-либо значение, например, в следующем коде:

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;
    }

Обычно эту проблему может решить изменение типа возвращаемого значения метода, чтобы он соответствовал типу в операторе возврата. Например, следующий void можно изменить на 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;
}

Прочтите эту статью:Как исправить ошибку «Невозможно вернуть значение из метода, тип результата которого недействителен»。

18. “Non-Static Variable … Cannot Be Referenced From a Static Context”

Эта ошибка возникает, когда компилятор пытается получить доступ к нестатической переменной в статическом методе:

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
    }
}

Чтобы устранить ошибку «Нестатическая переменная… На нее нельзя ссылаться из статического контекста», можно сделать две вещи:

  • Вы можете объявить переменные статическими.
  • Вы можете создавать экземпляры нестатических объектов в статических методах.

Пожалуйста, прочтите это руководство:Разница между статическими и нестатическими переменными。

19. “Non-Static Method … Cannot Be Referenced From a Static Context”

Эта проблема возникает, когда код Java пытается вызвать нестатический метод в статическом классе. Например, такой код:

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());
   }
}

Вызовет эту ошибку:

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

Чтобы вызвать нестатический метод в статическом методе, необходимо объявить экземпляр класса вызываемого нестатического метода.

Прочтите эту статью:Разница между нестатическими и статическими методами。

20. “(array) Not Initialized”

Если массив был объявлен, но не инициализирован, вы получите сообщение об ошибке типа «(массив) не инициализирован». Длина массива фиксирована, поэтому каждый массив необходимо инициализировать требуемой длиной.

Следующий код правильный:

AClass[] array = {object1, object2}

это тоже нормально:

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

Но это не так:

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

Прочтите эту статью:О том, как инициализировать массив в Java。

Продолжение следует

Сегодня мы обсуждали ошибки компилятора, в следующий раз мы обсудим различные исключения времени выполнения, которые могут возникнуть. Как и структура этой статьи, в следующий раз она будет содержать фрагменты кода, пояснения и ссылки по теме, которые помогут вам исправить код как можно скорее.

Понравилась статья? Поделить с друзьями:
  • Error incompatible types in assignment
  • Error incompatible types got single expected smallint
  • Error incompatible types got real expected smallint
  • Error incompatible types got extended expected smallint
  • Error incompatible types got extended expected longint