Error integer number too large

public class Three { public static void main(String[] args) { Three obj = new Three(); obj.function(600851475143); } private Long function(long i) { Stack<L...
public class Three {
    public static void main(String[] args) {
        Three obj = new Three();
        obj.function(600851475143);
    }

    private Long function(long  i) {
        Stack<Long> stack = new Stack<Long>();

        for (long j = 2; j <= i; j++) {
            if (i % j == 0) {
                stack.push(j);
            }
        }
        return stack.pop();
    }
}

When the code above is run, it produces an error on the line obj.function(600851475143);. Why?

tobias_k's user avatar

tobias_k

80.4k11 gold badges117 silver badges178 bronze badges

asked Sep 21, 2010 at 6:18

user446654's user avatar

5

600851475143 cannot be represented as a 32-bit integer (type int). It can be represented as a 64-bit integer (type long). long literals in Java end with an «L»: 600851475143L

answered Sep 21, 2010 at 6:20

Yuliy's user avatar

YuliyYuliy

17.2k6 gold badges41 silver badges47 bronze badges

Append suffix L: 23423429L.

By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L for long values.

answered Sep 21, 2010 at 6:20

Roman's user avatar

RomanRoman

63.3k91 gold badges234 silver badges328 bronze badges

1

You need to use a long literal:

obj.function(600851475143l);  // note the "l" at the end

But I would expect that function to run out of memory (or time) …

answered Sep 21, 2010 at 6:20

Thilo's user avatar

ThiloThilo

254k99 gold badges502 silver badges649 bronze badges

3

The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.

To tell the compiler that you want the number interpretet as a long you have to add either l or L after it. Your number should then look like this 600851475143L.

Since some Fonts make it hard to distinguish «1» and lower case «l» from each other you should always use the upper case «L».

answered Sep 21, 2010 at 6:29

josefx's user avatar

josefxjosefx

15.4k6 gold badges36 silver badges61 bronze badges

You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).

This has nothing to do with function. Try using a long integer literal instead (as suggested in the other answers).

answered Sep 21, 2010 at 6:22

Andre Holzner's user avatar

Andre HolznerAndre Holzner

18.1k6 gold badges53 silver badges62 bronze badges

At compile time the number «600851475143» is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.

answered Sep 21, 2010 at 11:59

JVM's user avatar

JVMJVM

2291 silver badge2 bronze badges

Apart from all the other answers, what you can do is :

long l = Long.parseLong("600851475143");

for example :

obj.function(Long.parseLong("600851475143"));

answered Jan 22, 2017 at 13:33

Anand Undavia's user avatar

Anand UndaviaAnand Undavia

3,4035 gold badges19 silver badges33 bronze badges

1

Or, you can declare input number as long, and then let it do the code tango :D

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter a number");
    long n = in.nextLong();

    for (long i = 2; i <= n; i++) {
        while (n % i == 0) {
            System.out.print(", " + i);
            n /= i;
        }
    }
}

answered Jun 25, 2017 at 8:21

Milen.Jeremic's user avatar

1. Overview

Java stores Integer using 32 bits of memory. Thus, Integer‘s(or int‘s) range is from -231 (-2,147,483,648) to 231-1 (2,147,483,647)Therefore, when we see an error message like “java: integer number too large …“, we can usually easily find the problem and fix it.

However, in some cases, when we see this error message, we might not understand why the error occurred. And it’ll take some time to fix the problem.

So, in this tutorial, we’ll take a closer look at a couple of pitfalls that lead to this error and address the reason behind the error.

2. Integer Literals Pitfall #1

The Java compiler complains when we assign a literal number out of the mentioned integer range to an int variable. For example, let’s say we compile this assignment:

int a = 12345678912345;

The compiler reports this error:

java: integer number too large

We can quickly find the problem by reading the error message. We may think int is not the right type for such a big number, so we change the type to long:

long a = 12345678912345;

However, when we recompile the code, we get the same compilation error: “integer number too large“. We’ll wonder why the compiler still complains about integer, although we declared the variable as long? Next, we may spend some time double-checking if we saved the file correctly or restarting the IDE, and so on. However, the problem still stays.

When we write number literals in Java, no matter whether it’s within or outside the integer range, Java treats it as the Integer/int type. If we want an integer literal to be long, we must add the ‘L‘ or ‘l‘ suffix. This is also explicitly stated in the Java Language Specification:

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int

Therefore, to fix the problem, we should add an ‘L‘ after the literal number:

long a = 12345678912345L;

It’s worth mentioning when we use decimal literals without any suffix, Java treats them as double. In case we want them to be float, we must add an ‘F‘ or ‘f‘ suffix:

float a = 1024.42; // compiler error -  java: incompatible types: possible lossy conversion from double to float
float a = 1024.42F; // compiled

3. Integer Literals Pitfall #2

Now we understand that we should add the ‘L‘ suffix to integer literals for the long type. Next, let’s see another example:

long a = 007L;

As the code above shows, we have the suffix ‘L‘ this time, and a‘s type is long. The code compiles smoothly even if there are leading zeros. If we check a’s value, the variable a holds 7, as expected. So, we may think Java is so intelligent that it ignores the leading zeros of numbers.

Now, let’s declare another variable:

long b = 008L;

Again, the compiler reports “integer number too large” if we compile the code.

This time, there’s no sign of an integer in our code. Furthermore, long a = 007L; has worked without any problem. Why does long b = 008L fail? It may take some time to solve the problem.

Actually, we’ve fallen into another integer literals pitfall. This is because, in Java, an integer literal can also be expressed in octal (base 8) . Further, an octal integer consists of a leading zero followed by one or more of the digits 0 through 7.

Therefore, everything’s fine when we assign ‘007L‘ to a variable. This is because Java reads the octal integer literal ‘007′, and treats it as long. However, when we assign ‘008L‘ to a variable, 008 is not a valid octal integer. Thus, the compiler reports that error.

After we understand the cause of the problem, the fix is pretty simple – removing the leading zeros:

long b = 8L;

4. Conclusion

In this article, we’ve discussed two common pitfalls when we work with integer literals in Java.

Understanding the reason behind the compilation error may help us find and fix the problem quickly.

In this short post, I will be sharing how to fix «integer number too large». This error is a compile-time error in Java. This error occurs when the java compiler tries to interpret the given number as a constant value of type int by default. As always, first, we will produce the «integer number too large» error before moving on to the solution.

Read Also: [Fixed] int cannot be converted to int[]

[Fixed]: Error: Integer number too large

Example 1: Producing the error by assigning an int to a long data type

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

public class IntegerNumberTooLarge {
    public static void main(String args[]) {
      

long x = 123456789101112;

System.out.println("variable x value is: " + x); } }

Output:
IntegerNumberTooLarge.java:3: error: integer number too large
           long x = 123456789101112;
                          ^
1 error

Explanation:

The cause of this error is by assigning an int to a variable whose data type is long. Integer literals are by default int in Java. This causes an error since 123456789101112 literal can not be represented with an int.

Solution:

The solution to this error is to append «l» or «L» after the number. Use «L» instead of «l» because lowercase «l» makes it hard to distinguish with «1», as a result, you should always use the uppercase «L». In Java, the compiler can interpret the long data type as long as the number to be interpreted contains ‘l’ or ‘L’ after it. It can be represented in the code as shown below:

public class IntegerNumberTooLarge {
    public static void main(String args[]) {
      

long x = 123456789101112L;

System.out.println("variable x value is: " + x); } }

Output:
variable x value is: 123456789101112

That’s all for today, please mention in the comments in case you are still facing the error java integer number too large.

Java Basic data Types (let’s start with Java basic data types)
A variable is a memory request to store a value. That is, when creating variables, you need to request space in memory.
The memory management system allocates storage space for variables based on their type, which can only be used to store data of that type.

Therefore, by defining different types of variables, you can store integers, decimals, or characters in memory.
The two big data types in Java:
Built-in data types refer to data types


Built-in data type
The Java language provides eight basic types. There are six numeric types (four integers, two floats), one character type, and one Boolean type.
Byte:
A byte data type is an 8-bit, signed integer represented by a binary complement; The minimum is minus 128 times minus 2 to the seventh; The maximum is 127 (2^7-1); The default value is 0; Byte is used in large arrays to save space, replacing integers because byte variables take up only a quarter of the space of an int. Example: Byte a = 100, byte B = -50.
Short:
The minimum value of a 16-bit, signed integer represented by binary complement is -32768 (-2^15). The maximum is 32767 (2^15-1); Short data types can also save as much space as a byte. A short variable is one half of the space occupied by an int variable. The default value is 0; Example: Short s = 1000, short r = -20000.
Int:
The int data type is a 32-bit, signed integer represented as a binary complement; The minimum is -2,147,483,648 (-2^31); The maximum value is 2,147,483,647 (2^ 31-1); Generally, integer variables default to int; The default value is 0; Example: int a = 100000, int B = -200000.
Long:
The long data type is a 64-bit, signed integer represented as a binary complement; The minimum value is – 9223372036854775808 (2 ^ 63); Maximum is 9223372036854775807 (2 ^ 63-1); This type is mainly used on systems that require larger integers; The default value is 0L; Example: long A = 100000L, long B = -200000l.
“L” is not case-sensitive in theory, but if written as “L”, it is easy to confuse with the number “1” and cannot be easily distinguished. So it’s better to capitalize.
Float:
The float data type is a single-precision, 32-bit, IEEE 754 compliant float; Floats save memory when storing large floating point arrays. The default value is 0.0f; Floating-point Numbers cannot be used to represent exact values, such as currency; Example: Float F1 = 234.5F.
Double:
A double data type is a double-precision, 64-bit, IEEE 754 compliant floating point; The default type of floating-point Numbers is double; Double also does not represent exact values, such as currency; The default value is 0.0d; Example: Double D1 = 123.4.
Boolean:
Boolean data types represent bits of information; There are only two values: true and false; This type is used only as a flag to record true/false cases; The default value is false; Example: Boolean One = true.
Char:
Char is a single 16-bit Unicode character; The minimum value is u0000 (i.e., 0); The maximum value is UFFFF (i.e. 65,535); Char data type can store any character; Char letter = ‘A’;

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Defined in Java:
Long len = 12345678901211;
Result error:
Error: Integer Number too Large: 12345678901211
Correct writing: long len = 12345678901211L;
Reason: The L is treated as long; If you do not add it and treat it as an int, an error will be reported.
 

Read More:

We know that the maximum value of an int is 2147483647. If we write any whole number more than 2147483647 in our Java program, we may get this error message ‘integer number too large’ but may be you are trying to store this large number in a long type variable, then what to do? The solution is to put the letter ‘l’ or ‘L’ after the number. This happens, because the compiler considers the whole number as int by default and we specify the large number by character ‘l’ or ‘L’ as long number. Now the compiler will consider the number as long.

For example, we are trying to compile the following Java code:

public class IntegerNumberTooLarge
{
public static void main(String args[])
{
long number=965478213245;
System.out.println(number);
}
}

We will get ‘integer number too large’ from the above program. Now write the program as below the problem will be solved.

public class IntegerNumberTooLargeSolution
{
public static void main(String args[])
{
long number=965478213245L;
System.out.println(number);
}
}

Из песочницы, Программирование, Java, Проектирование и рефакторинг


Рекомендация: подборка платных и бесплатных курсов PR-менеджеров — https://katalog-kursov.ru/

Здравствуйте. Хочу представить вашему вниманию небольшую статью. Статья предназначена для начинающих. Но даже, если вы опытный разработчик, не делайте поспешных выводов.
Надеюсь данная публикация будет полезна не только начинающим.

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

Подводные камни Java

Все языки программирования имеют свои достоинства и недостатки. Это обусловлено многими причинами. Язык Java не исключение. Я попытался собрать некоторые очевидные и не очевидные трудности, с которыми сталкивается начинающий программист Java. Уверен, что опытные программисты тоже найдут в моей статье что-то полезного. Практика, внимательность и полученный опыт программирования, помогут избавить вас от многих ошибок. Но некоторые ошибки и трудности лучше рассмотреть заранее. Я приведу несколько примеров с кодом и объяснениями. Многие объяснения вам станут понятны из комментариев к коду. Практика дает очень многое, так как некоторые правила не столь очевидны. Некоторые лежат на поверхности, некоторые скрыты в библиотеках языка или в виртуальной машине java. Помните, что java это не только язык программирования с набором библиотек, это еще и виртуальная машина java.

Для статьи я специально написал работающий код с подробными комментариями. Для написания статьи использовалась java 8. Для тестирования код java помещен в отдельные пакеты.

Пример: «package underwaterRocks.simple;»

С какими трудностями сталкиваются начинающие?

Опечатки

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

Пример кода:

Файл: «Simple.java»

/*
учебные пример
; после условия и блок 
*/
package underwaterRocks.simple;

/**
 *
 * @author Ar20L80
 */
public class Simple {
    public static void main(String[] args) {
        int ival = 10;
        if(ival>0);
        {
            System.out.println("Этот блок не зависит от условия");
        }
    }
}

Объяснение: «Точка с запятой означает конец оператора. В данном случае; — это конец пустого оператора. Это логическая ошибка. Такую ошибку бывает трудно обнаружить.

Компилятор сочтет, что всё правильно. Условие if(ival>0); в данном случае не имеет смысла. Потому как означает: если ival больше нуля, ничего не делать и продолжить.»

Присвоение в условии вместо сравнения

В условии присвоение переменной.

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

 boolean myBool = false;
if(myBool = true) System.out.println(myBool);

В данном коде if(myBool = true) означает :«Присвоить переменной myBool значение true,
если выражение истинно, выполнить условие следующее за скобками.»

В данном коде условие будет всегда истинно. И System.out.println(myBool); будет выполнено всегда, независимо от условия.

== — это сравнение на равенство.
= — это присвоение, вы можете проговорить a = 10; как: «а присвоить значение 10».

Условие в скобках возвращает логическое значение.
Не важно в каком порядке вы запишите. Вы можете сравнить так: (0 == a) или (5 == a)
Если вы забудете один знак равенства, например так (0 = a) или (5 = a), то компилятор сообщит вам об ошибке. Вы присваиваете значение, а не сравниваете.
Вы также можете записать в удобочитаемой форме какой-то интервал.
Например: вам нужно написать: a больше 5 и меньше 10.
Вы пишите так: (a>4 && a<10), но с таким же успехом вы можете написать: (4<a && a<10),
теперь вы видите, что a находится в интервале между 4 и 10, исключая эти значения. Это более наглядно. Сразу видно, что а находится в интервале между 4 и 10, исключая эти значения.

Пример в коде(интервал ]3,9[ ):
if(3<a&&a<9) выполнить;

Логическая ошибка

if(условие){} if(условие){} else{} — else относится к ближайшему if.
Часто это бывает причиной ошибок начинающих.

Неправильное сравнение строк

Начинающие довольно часто используют == вместо .equals для сравнения строк.

Инициализация переменных

Рассмотрим инициализацию переменных примитивного типа.

Примитивы (byte, short, int, long, char, float, double, boolean).

Начальные значения.

byte	0
short	0
int	0
long	0L
float	0.0f
double	0.0d
char	'u0000'
String (or any object)  	null
boolean	false (зависит от jvm)

Примечание:

Локальные переменные немного отличаются;
Компилятор никогда не присваивает значение по умолчанию неинициализированной локальной переменной.

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

Доступ к неинициализированной локальной переменной приведет к ошибке времени компиляции.

Подтверждение этого примечания в коде:

Файл: «MyInitLocal.java»

/*
учебные пример
инициализация переменных класса и локальных переменных
 */
package underwaterRocks.myInit;

/**
 *
 * @author Ar20L80
 */
public class MyInitLocal {
    float classes_f;
    int classes_gi;
    public static void main(String[] args) {
        float f;
        int i;
        MyInitLocal myInit = new MyInitLocal();
        
        /* в этом месте переменные уже инициализированы параметрами по умолчанию.*/
        System.out.println("myInit.classes_f = " + myInit.classes_f);
        System.out.println("myInit.classes_gi = " + myInit.classes_gi);
        
      //  System.out.println("f = " + f); // ошибка. Локальная переменная не инициализирована
      //  System.out.println("f = " + i); // ошибка. Локальная переменная не инициализирована
        
    }
}

Диапазоны значений:

byte (целые числа, 1 байт, [-128, 127])
short (целые числа, 2 байта, [-32768, 32767])
int (целые числа, 4 байта, [-2147483648, 2147483647])
long (целые числа, 8 байт, [-922372036854775808,922372036854775807])
float (вещественные числа, 4 байта)
double (вещественные числа, 8 байт)
char (символ Unicode, 2 байта, 16 бит, [0, 65535])
boolean (значение истина/ложь, используется int, зависит от JVM)

char: The char data type is a single 16-bit Unicode character. It has a minimum value of ‘u0000’ (or 0) and a maximum value of ‘uffff’ (or 65,535 inclusive).

Документация Oracle >>

Попытаемся инициализировать переменную типа long числом: 922372036854775807.
У нас ничего не выйдет. Потому как, это целочисленный литерал типа int.
Правильная инициализация литералом типа long: 922372036854775807L;

Пример кода:

Файл: «MyInitLocalLong.java»

/*
 учебные пример
 Инициализация long локально 
 */
package underwaterRocks.myInit;

/**
 *
 * @author Ar20L80
 */
public class MyInitLocalLong {
    public static void main(String[] args) {
      //  long al = 922372036854775807; //ошибка integer number too large
        long bl = 922372036854775807L; // так правильно  
    }
}

На что следует обращать внимание при инициализации переменной.

На диапазон значений переменной данного типа. На то, что переменная инициализируется литералом определенного типа. На явное и неявное приведение типов. На совместимость типов.

При использовании оболочек типа Integer, следует обратить внимание на авто упаковку и авто распаковку данных типов.

Неправильное использование double

Здесь нужно пояснить. Речь идет не о неправильном использовании типа double.
Используем мы правильно. Только результат может удивить начинающего программиста.

/*
  учебный пример 
 */
package underwaterRocks.tstDouble;

/**
 *
 * @author vvm
 */
public class MinusDouble {
    public static void main(String[] args) {
        double a = 4.64;
        double b = 2.64;
        System.out.println("a-b = "+(a-b));
    }
}
/*
Вывод программы
run:
a-b = 1.9999999999999996
*/

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

Неправильное сравнение double

Рассмотрим тип double.

Пример кода:

Файл: «MyDouble.java»


/*
 учебные пример
 Сравнение double
 Осторожно - double.
 */
package underwaterRocks.myDouble;

/**
 *
 * @author Ar20L80
 */
public class MyDouble {
    public static void main(String[] args) {
        double dx = 1.4 - 0.1 - 0.1 - 0.1 - 0.1;
        System.out.println("dx = " + dx); // dx = 0.9999999999999997
        System.out.print("Сравнение (dx == 1.0):");
        System.out.println(dx == 1.0); // false, потому что 1.0 не равно 0.9999999999999997
        
        /*как правильно сравнивать double*/
        final double EPSILON = 1E-14;
        double xx = 1.4 - 0.1 - 0.1 - 0.1 - 0.1;
        double xy = 1.0;
        /* сравниваем xx c xy */
        if (Math.abs(xx - xy) < EPSILON)
            System.out.println(xx + " это примерно равно " + xy + " EPSILON = " + EPSILON);
    } 
}
 

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

Конструктор класса

Конструктор класса совпадает с именем класса и ничего не возвращает, даже void.

Пример кода:

Файл: «MyConstructor.java»


/*
 учебные пример
 Конструктор ничего не возвращает, даже void
 То что с void  - обычный метод класса
 */
package underwaterRocks.myConstructor;

/**
 *
 * @author Ar20L80
 */
public class MyConstructor {
    public MyConstructor(){
        System.out.println("Я конструктор без void");
    }
    public void MyConstructor(){
        System.out.println("Я конструктор c void");
    }
    public static void main(String[] args) {
        MyConstructor myconst = new MyConstructor();
        myconst.MyConstructor(); // вызов обычного метода
    }
}

Как мы видим в коде два метода с одинаковыми именами: MyConstructor() и MyConstructor(). Один из методов ничего не возвращает. Это и есть конструктор нашего класса. Другой метод с void — это обычный метод класса. В случае, когда вы не создали конструктор или создали, по вашему мнению конструктор класса с void, то компилятор создаст конструктор по умолчанию и вы будете удивлены, почему ваш конструктор не работает.

Деление на ноль

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

Файл: «DivisionByZero.java»

/*учебные пример*/
package divisionByZero;
import static java.lang.Double.POSITIVE_INFINITY;

/**
 *
 * @author Ar20L80
 */
public class DivisionByZero {
    public static void main(String[] args) {
    try{
        float f = 12.2f;
        double d = 8098098.8790d;
        System.out.println(f/0); 
        System.out.println(d/0);  
        System.out.println(POSITIVE_INFINITY == f/0);
        System.out.println(POSITIVE_INFINITY == d/0);
    }
    catch (NumberFormatException ex) { 
            System.out.println("NumberFormatException"); 
        } 
        catch (ArithmeticException ex) { 
            System.out.println("ArithmeticException"); 
        }  
    }
    
}

Выполнение кода выведет:

Infinity
Infinity
true
true

Деление целого типа на ноль даст ArithmeticException.

В классе java.lang.Double определена константа POSITIVE_INFINITY;

public static final float POSITIVE_INFINITY = 1.0d / 0.0d; 

Она преобразуется в строку равную Infinity.

Порядок инициализации

Файл: «InitClass.java»

/*
 учебные пример
 инициализация класса
 */
package myInitClass;

/**
 *
 * @author Ar20L80
 */
public class InitClass {
    InitClass(){ // конструктор класса
        System.out.print("Конструктор"); 
    }
    { // блок инициализации
        System.out.print("3 "); 
    } 
    
    public static void main(String[] args) { 
        System.out.print("2"); 
        new InitClass(); 
    } 
    
    static { // статический блок инициализации
        System.out.print("1"); 
    } 
}

Вначале выполняются все статические блоки, затем блоки инициализации, затем конструктор класса.

Выведется: «123 Конструктор»

Локальная переменная скрывает переменную класса
Хотя современные IDE легко обнаруживают такую ошибку, хотелось бы рассмотреть такую ошибку подробнее. Начнем с классического присвоения переменной в конструкторе. Пример правильный. Тут никакой ошибки нет.

 public class MyClass {
   private int val = 0;

   public MyClass(int val) {
      this.val = val;
   }
}
 

Однако, что произойдет, если вы используете такой прием в методе, а не в конструкторе класса? В обычном методе использовать такой прием не рекомендуется. Вопрос относится к правильному проектированию класса.

Простое объяснение: В методе переменная с тем же именем, что и переменная класса, является локальной по отношению к методу. Вы можете обращаться к переменной класса используя this.val. Однако такое обращение из метода, при неправильном проектировании класса только вызовет побочные эффекты и может ухудшить читаемость кода.

Приведение типов в арифметических выражениях выполняется автоматически

Это может стать причиной досадных ошибок.

        
         // byte a = 1;
        // byte b = 1;
        // byte с = a + b; // ошибка

        //  byte a = (byte) 1;
        // byte b = (byte) 1;
        //  byte с = a + b; // ошибка
    
      // одно из возможных решений - явное преобразование в арифметических выражениях.
        byte a = 1;
        byte b = 1;
        byte c = (byte) (a + b);
   
    
        // одно из возможных решений - использование final
        // final byte a = 1;
        // final byte b = 1;
        // byte c = a + b; // автоматического приведения не будет, поскольку a и b final
    

Одно из возможных решений при работе со строкой:

byte bHundr = Byte.parseByte("100"); //  явное приведение строки к типу byte

Еще одна ошибка приведена в следующем коде.

for (byte i = 1; i <= 128; i++) {
            System.out.println(i);
        }

В данном случае получится бесконечный цикл.

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

Надеюсь, статья вам понравилась и оказалась полезной. Буду рад вашим комментариям, замечаниям, предложениям, пожеланиям. Продолжение следует. Вернее дополнение следует.

Лицензия
«Я разрешаю читать эту статью, разрешаю использовать эту статью, позволяю улучшать эту статью». Статья распространяется на условиях GNU FDL.

Ссылки
Рекомендации об оформлении кода на Javа от Oracle >>>

Понравилась статья? Поделить с друзьями:
  • Error insufficient privileges to write to macports install prefix
  • Error insufficient permission for adding an object to repository database git objects
  • Error insufficient pci resources detected как исправить
  • Error insufficient memory как исправить принтер
  • Error insufficient memory reserved for statement