Here, we will follow the below-mentioned points to understand and eradicate the error alongside checking the outputs with minor tweaks in our sample code
- Introduction about the error with example
- Explanation of dereferencing in detail
- Finally, how to fix the issue with Example code and output.
If You Got this error while you’re compiling your code? Then by the end of this article, you will get complete knowledge about the error and able to solve your issue, lets start with an example.
Example 1:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int sum = a + b;
System.out.println(sum.length);
}
}
Output:

So this is the error that occurs when we try to dereference a primitive. Wait hold on what is dereference now?. Let us do talk about that in detail. In Java there are two different variables are there:
- Primitive [byte, char, short, int, long, float, double, boolean]
- Objects
Since primitives are not objects so they actually do not have any member variables/ methods. So one cannot do Primitive.something(). As we can see in the example mentioned above is an integer(int), which is a primitive type, and hence it cannot be dereferenced. This means sum.something() is an INVALID Syntax in Java.
Explanation of Java Dereference and Reference:
- Reference: A reference is an address of a variable and which doesn’t hold the direct value hence it is compact. It is used to improve the performance whenever we use large types of data structures to save memory because what happens is we do not give a value directly instead we pass to a reference to the method.
- Dereference: So Dereference actually returns an original value when a reference is Dereferenced.
What dereference Actually is?
Dereference actually means we access an object from heap memory using a suitable variable. The main theme of Dereferencing is placing the memory address into the reference. Now, let us move to the solution for this error,
How to Fix “int cannot be dereferenced” error?
Note: Before moving to this, to fix the issue in Example 1 we can print,
System.out.println(sum); // instead of sum.length
Calling equals() method on the int primitive, we encounter this error usually when we try to use the .equals() method instead of “==” to check the equality.
Example 2:
Java
public class GFG {
public static void main(String[] args)
{
int gfg = 5;
if (gfg.equals(5)) {
System.out.println("The value of gfg is 5");
}
else {
System.out.println("The value of gfg is not 5");
}
}
}
Output:

Still, the problem is not fixed. We can fix this issue just by replacing the .equals() method with”==” so let’s implement “==” symbol and try to compile our code.
Example 3:
Java
public class EqualityCheck {
public static void main(String[] args)
{
int gfg = 5;
if (gfg == 5)
{
System.out.println("The value of gfg is 5");
}
else
{
System.out.println("The value of gfg is not 5");
}
}
}
Output
The value of gfg is 5
This is it, how to fix the “int cannot be dereferenced error in Java.
I’m fairly new to Java and I’m using BlueJ. I keep getting this «Int cannot be dereferenced» error when trying to compile and I’m not sure what the problem is. The error is specifically happening in my if statement at the bottom, where it says «equals» is an error and «int cannot be dereferenced.» Hope to get some assistance as I have no idea what to do. Thank you in advance!
public class Catalog {
private Item[] list;
private int size;
// Construct an empty catalog with the specified capacity.
public Catalog(int max) {
list = new Item[max];
size = 0;
}
// Insert a new item into the catalog.
// Throw a CatalogFull exception if the catalog is full.
public void insert(Item obj) throws CatalogFull {
if (list.length == size) {
throw new CatalogFull();
}
list[size] = obj;
++size;
}
// Search the catalog for the item whose item number
// is the parameter id. Return the matching object
// if the search succeeds. Throw an ItemNotFound
// exception if the search fails.
public Item find(int id) throws ItemNotFound {
for (int pos = 0; pos < size; ++pos){
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
return list[pos];
}
else {
throw new ItemNotFound();
}
}
}
}
asked Oct 1, 2013 at 6:08
1
id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :
id.equals
Try replacing this:
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
with
if (id == list[pos].getItemNumber()){ //Getting error on "equals"
answered Oct 1, 2013 at 6:10
![]()
Juned AhsanJuned Ahsan
67.1k11 gold badges96 silver badges134 bronze badges
2
Basically, you’re trying to use int as if it was an Object, which it isn’t (well…it’s complicated)
id.equals(list[pos].getItemNumber())
Should be…
id == list[pos].getItemNumber()
answered Oct 1, 2013 at 6:10
![]()
MadProgrammerMadProgrammer
340k22 gold badges225 silver badges355 bronze badges
4
Dereferencing is the process of accessing the value referred to by a reference . Since, int is already a value (not a reference), it can not be dereferenced.
so u need to replace your code (.) to(==).
answered Feb 21, 2022 at 5:20
![]()
Assuming getItemNumber() returns an int, replace
if (id.equals(list[pos].getItemNumber()))
with
if (id == list[pos].getItemNumber())
answered Oct 1, 2013 at 6:10
John3136John3136
28.5k4 gold badges49 silver badges68 bronze badges
Change
id.equals(list[pos].getItemNumber())
to
id == list[pos].getItemNumber()
For more details, you should learn the difference between the primitive types like int, char, and double and reference types.
answered Oct 1, 2013 at 6:11
Code-ApprenticeCode-Apprentice
79.8k21 gold badges139 silver badges256 bronze badges
As your methods an int datatype, you should use «==» instead of equals()
try replacing this
if (id.equals(list[pos].getItemNumber()))
with
if (id.equals==list[pos].getItemNumber())
it will fix the error .
answered Jun 23, 2018 at 14:59
AshitAshit
596 bronze badges
try
id == list[pos].getItemNumber()
instead of
id.equals(list[pos].getItemNumber()
answered Oct 1, 2013 at 6:12
![]()
Ali HashemiAli Hashemi
3,0183 gold badges33 silver badges47 bronze badges
- Dereferencing in Java
- Cause of
int cannot be dereferencedin Java - Solve the
int cannot be dereferencedError in Java

In this article, we’ll discuss the cause of the Java int cannot be dereferenced exception and how to fix it. First, have a look at what dereferencing in Java is.
Dereferencing in Java
Primitive and object variables are the two types of variables that can be used in Java. However, only object variables can be reference types. The int data type is a primitive rather than an object.
Accessing the value that is pointed to by a reference is what’s known as dereferencing. It is impossible to dereference int because it is already a value and is not a reference to anything else.
Cause of int cannot be dereferenced in Java
- A reference in Java is an address that points to a specific object or variable. The term dereferencing refers to obtaining an object’s properties through a reference.
- If you try to perform any dereferencing on a primitive, like the below example, you will receive the error
Zcannot be dereferenced, whereZis a type considered primitive. - The cause for this is that primitives are not the same thing as objects; instead, they are raw value representations.
Solve the int cannot be dereferenced Error in Java
Let’s understand int cannot be dereferenced and figure out how to fix it with the help of the example below:
Example:
public class Main {
public static void main(String[] args) {
int Z = 8;
System.out.println(Z.equals(8));
}
}
Firstly, we created the Main class and compared an int to a value chosen at random. Z is one of Java’s eight fundamental data types, including int, byte, short, etc.
We will see the following error when we attempt to compile the code:
Main.java:5: error: int cannot be dereferenced
System.out.println(Z.equals(8));
^
1 error
In our case, we need to determine whether or not the two values are equal. Solving our issue is to utilize the notation == rather than the equals() function for primitive types:
public class Main {
public static void main(String[] args) {
int Z = 8;
System.out.println(Z == 8);
}
}
The following output will be printed when we compile the code:
When we tried to use Primitive types as objects and perform operations on them that are applicable to objects, we ran into dereferenced problems.
Before we get into the specifics of what’s causing the current dereferenced situation, let’s define what dereferenced implies.
When we construct an object, heap memory is allocated and a reference to this heap memory is generated in the stack.
Once we create an object it allocates space in heap memory and a reference is created in the stack pointing to this heap memory. To put it another way, an object reference is used to set or get the values of an object.
However, because a primitive type variable is a value rather than an object, it cannot be used with object methods such as length(), equals(), getClass(), toString(), and other object methods.
It also tells us that everything in java is not an object 🙂
Let’s look at some common issues that result int cannot be dereferenced and understand the root cause with solutions.
- How to solve int cannot be dereferenced toString in Java?
- What is Null pointer dereference?
- How to fix the dereferenced error with the equals method in java?
- To brush up on your knowledge on this subject, take the MCQ at the End of this Article.
- Feedback: Your input is valuable to us. Please provide feedback on this article.
I’m assuming we’re already aware that the toString method converts applied objects to strings. Please take note of the word «applied objects,» which implies that toString should only be used with objects.
To illustrate the reason and possible remedy, consider the following example, which includes generating a dereferenced error.

Explanation :
- checkMe is an int primitive type that has been defined.
- Applied toString method on the primitive type.
- Received dereferenced error because checkMe is not representing reference of object hence it companies and raises an error.
While we develop programs as described above, most of the newer IDEs prompt errors. Using the valueOf method, one of the possible solutions to the above failure is shown below.
int testMe = 10; System.out.println(Integer.valueOf(testMe).getClass().getSimpleName()); System.out.println(Integer.valueOf(testMe).toString()); System.out.println(Integer.valueOf(testMe).toString().getClass().getSimpleName()); Result: Integer 10 String
Explanation:
- We can use the Integer.valueOf method to acquire the Integer instance of the specified int value.
- After receiving an instance via Integer.valueOf method we can access an object inbuilt method like getClass(), getSimpleName() and toString() to get the desired Class simple name and string version of Integer object.
When objects are created, they are pointed�by references in the stack. So, in order to access an object’s inbuilt method, it should be dereferenced. When we try to manipulate non-reference objects data, we receive a NullPointerException, which causes the program to exit/crashes.
Consider the following scenario:
public class Professor {
public static void main(String[] args) {
Professor obj = new Professor();
System.out.println("Before setting obj null: " + System.identityHashCode(obj));
System.out.println("Class name: " + obj.getClass().getSimpleName());
obj = null; // Removing reference
System.out.println("After setting obj null: " + System.identityHashCode(obj));
System.out.println("Class name: " + obj.getClass().getSimpleName());
}
}
Result:
Before setting obj null: 1304836502
Class name: Professor
After setting obj null: 0
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "obj" is null
Explanation:
- Created class Professor for demonstration purpose
- Using the
System.identityHashCodemethod to check for Hash Code before and after setting null reference. - We can see that there is a valid reference to object obj in the result, and we can print the associated class name as Professor.
Once we’ve set a reference to null .�This indicates that the object no longer has a valid reference pointing to it.
As a result, if we try to use the object member method on a null reference, it will complain since it is attempting to dereference, which is not possible with primitive and null references.
As shown above, a NullPointerException will be thrown.
It’s possible that the reason for dereferenced is the same. Consider the following scenario:
int var = 10;
if (var.equals(10) ) {
}
Result: dereferenced error
Explanation:
- We’re trying to use primitive type variables (var) to access an Integer class method equals to compare two int values.
- Primitive types, as we learned at the beginning of this post, do not contain any member methods for manipulating values, such as equals, toString, and so on. As a result, a dereferenced error occurs.
Let’s look at how equals can be used to compare int numbers.
int var = 101;
Integer test = 10;
if (Integer.valueOf(var).equals(test) ) {
System.out.println("Given number is equal to 10");
} else {
System.out.println("Given number is not equal to 10");
}
Result: Given number is not equal to 10
Integer.valueOf returns an integer representation of an int value, which can then be compared using the equals method.
Yes, it was beneficial.
Yes, it was helpful, however more information is required.
It wasn’t helpful, so no.
Feedback (optional) Please provide additional details about the selection you chose above so that we can analyze the insightful comments and ideas and take the necessary steps for this topic. Thank you
Send Feedback
Содержание
- How to Handle the Incompatible Types Error in Java
- Introduction to Data Types & Type Conversion
- Incompatible Types Error: What, Why & How?
- Incompatible Types Error Examples
- Explicit type casting
- How to Fix int cannot be dereferenced Error in Java?
- Русские Блоги
- 20 распространенных ошибок Java и как их избежать
- Ошибка компилятора
- 1. “… Expected”
- 2. “Unclosed String Literal”
- 3. “Illegal Start of an Expression”
- 4. “Cannot Find Symbol”
- 5. “Public Class XXX Should Be in File”
- 6. “Incompatible Types”
- 7. “Invalid Method Declaration; Return Type Required”
- 8. “Method in Class Cannot Be Applied to Given Types”
- 9. “Missing Return Statement”
- 10. “Possible Loss of Precision”
- 11. “Reached End of File While Parsing”
- 12. “Unreachable Statement”
- 13. “Variable Might Not Have Been Initialized”
- 14. “Operator … Cannot be Applied to ”
- 15. “Inconvertible Types”
- 16. “Missing Return Value”
- 17. “Cannot Return a Value From Method Whose Result Type Is Void”
- 18. “Non-Static Variable … Cannot Be Referenced From a Static Context”
- 19. “Non-Static Method … Cannot Be Referenced From a Static Context”
- 20. “(array) Not Initialized”
- Продолжение следует
- Интеллектуальная рекомендация
- IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS
- Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis
- 1086 Не скажу (15 баллов)
- Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных
- 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].
Источник
How to Fix int cannot be dereferenced Error in Java?
Here, we will follow the below-mentioned points to understand and eradicate the error alongside checking the outputs with minor tweaks in our sample code
- Introduction about the error with example
- Explanation of dereferencing in detail
- Finally, how to fix the issue with Example code and output.
If You Got this error while you’re compiling your code? Then by the end of this article, you will get complete knowledge about the error and able to solve your issue, lets start with an example.
Example 1:
Output:
So this is the error that occurs when we try to dereference a primitive. Wait hold on what is dereference now?. Let us do talk about that in detail. In Java there are two different variables are there:
- Primitive [byte, char, short, int, long, float, double, boolean]
- Objects
Since primitives are not objects so they actually do not have any member variables/ methods. So one cannot do Primitive.something(). As we can see in the example mentioned above is an integer(int), which is a primitive type, and hence it cannot be dereferenced. This means sum.something() is an INVALID Syntax in Java.
Explanation of Java Dereference and Reference:
- Reference: A reference is an address of a variable and which doesn’t hold the direct value hence it is compact. It is used to improve the performance whenever we use large types of data structures to save memory because what happens is we do not give a value directly instead we pass to a reference to the method.
- Dereference: So Dereference actually returns an original value when a reference is Dereferenced.
What dereference Actually is?
Dereference actually means we access an object from heap memory using a suitable variable. The main theme of Dereferencing is placing the memory address into the reference. Now, let us move to the solution for this error,
How to Fix “int cannot be dereferenced” error?
Note: Before moving to this, to fix the issue in Example 1 we can print,
Calling equals() method on the int primitive, we encounter this error usually when we try to use the .equals() method instead of “==” to check the equality.
Источник
Русские Блоги
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.
Источник