Как проверить Long на нуль в Java
Примитивные типы данных не могут быть null . Только типы данных Object могут быть null .
int , long и т. Д. Не может быть null .
Если вы используете Long (класс-оболочку для long ), вы можете проверить наличие null :
Если переменная longValue имеет тип Long (класс-оболочка, а не примитив long ), то да, вы можете проверить нулевые значения.
Примитивная переменная должна быть явно инициализирована некоторым значением (например, 0 ), чтобы ее значение никогда не было нулевым.
Вы можете проверить объект Long на наличие нулевого значения с помощью longValue == null , вы можете использовать longValue == 0L для long (примитив), потому что значение long по умолчанию — 0L, но результат будет истинным, если longValue тоже равно нулю
Конечно, примитивные типы не могут быть нулевыми. Но в Java 8 для проверки можно использовать Objects.isNull (longValue). Бывший. Если (Objects.isNull (longValue))
Как уже упоминалось, примитивы не могут быть установлены в тип объекта null.
В таких случаях я просто использую -1 или Long.MIN_VALUE .
Если это Long, вы можете проверить, является ли он нулевым, если вы не продержитесь долго (поскольку примитивные типы данных не могут быть нулевыми, в то время как экземпляр Long является объектом)
Для некоторого контекста вы также можете предпочесть использовать с ним Optional, чтобы сделать его каким-то красивым для некоторых случаев использования. Обратитесь к @RequestParam в Spring MVC, обрабатывающем дополнительные параметры
Поскольку примитивы (long) не могут быть нулевыми, они могут быть преобразованы в класс-оболочку этого примитивного типа (например, Long), и может быть выполнена проверка на null.
Если вы хотите проверить, является ли длинная переменная нулевой, вы можете преобразовать ее в Long и проверить,
Class Long
In addition, this class provides several methods for converting a long to a String and a String to a long , as well as other constants and methods useful when dealing with a long .
This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
Implementation note: The implementations of the «bit twiddling» methods (such as highestOneBit and numberOfTrailingZeros ) are based on material from Henry S. Warren, Jr.’s Hacker’s Delight, (Addison Wesley, 2002).
Field Summary
Constructor Summary
Method Summary
Methods declared in class java.lang.Object
Field Details
MIN_VALUE
MAX_VALUE
BYTES
Constructor Details
Method Details
toString
If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX , then the radix 10 is used instead.
If the first argument is negative, the first element of the result is the ASCII minus sign ‘-‘ ( ‘\u002d’ ). If the first argument is not negative, no sign character appears in the result.
The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the magnitude will not be the zero character. The following ASCII characters are used as digits:
toUnsignedString
If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX , then the radix 10 is used instead.
Note that since the first argument is treated as an unsigned value, no leading sign character is printed.
If the magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the magnitude will not be the zero character.
The behavior of radixes and the characters used as digits are the same as toString .
toHexString
The unsigned long value is the argument plus 2 64 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Long.parseUnsignedLong(s, 16) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as hexadecimal digits:
toOctalString
The unsigned long value is the argument plus 2 64 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in octal (base 8) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Long.parseUnsignedLong(s, 8) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as octal digits:
toBinaryString
The unsigned long value is the argument plus 2 64 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Long.parseUnsignedLong(s, 2) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters ‘0’ ( ‘\u0030’ ) and ‘1’ ( ‘\u0031’ ) are used as binary digits.
toString
toUnsignedString
parseLong
Note that neither the character L ( ‘\u004C’ ) nor l ( ‘\u006C’ ) is permitted to appear at the end of the string as a type indicator, as would be permitted in Java programming language source code — except that either L or l may appear as a digit for a radix greater than or equal to 22.
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX .
- Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ ( ‘\u002d’ ) or plus sign ‘+’ ( ‘\u002B’ ) provided that the string is longer than length 1.
- The value represented by the string is not a value of type long .
parseLong
The method does not take steps to guard against the CharSequence being mutated while parsing.
parseLong
Note that neither the character L ( ‘\u004C’ ) nor l ( ‘\u006C’ ) is permitted to appear at the end of the string as a type indicator, as would be permitted in Java programming language source code.
parseUnsignedLong
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX .
- Any character of the string is not a digit of the specified radix, except that the first character may be a plus sign ‘+’ ( ‘\u002B’ ) provided that the string is longer than length 1.
- The value represented by the string is larger than the largest unsigned long , 2 64 -1.
parseUnsignedLong
The method does not take steps to guard against the CharSequence being mutated while parsing.
Как проверить Лонг на ноль в Java
Примитивные типы данных не могут быть null . Только типы данных Object могут быть null .
int , long и т.д. не может быть null .
Если вы используете long (класс-оболочка для long ), вы можете проверить null ‘:
Если переменная longValue имеет тип Long (класс оболочки, а не примитив Long ), то да, вы можете проверить нулевые значения.
Первичная переменная должна быть инициализирована до некоторого значения явно (например, до 0 ), поэтому ее значение никогда не будет равно нулю.
Если это объект Long , то вы можете использовать longValue == null или вы можете использовать метод Objects.isNull(longValue) в Java 8.
Пожалуйста, просмотрите Объекты для получения дополнительной информации.
Вы можете проверить объект Long для нулевого значения с помощью longValue == null , вы можете использовать longValue == 0L для длинных (примитивных), потому что значение по умолчанию long равно 0L, но результат будет true, если longValue тоже равно нулю
Конечно, примитивные типы не могут быть нулевыми. Но в Java 8 вы можете использовать Objects.isNull(longValue) для проверки. Ex. Если (Objects.isNull(longValue))
Как уже упоминалось, примитивы не могут быть установлены на тип объекта null.
В таких случаях я просто использую -1 или Long.MIN_VALUE .
Так как примитивы (long) не могут быть нулевыми, они могут быть преобразованы в класс-оболочку этого типа примитивов (например, Long), и может быть выполнена проверка на null.
Если вы хотите проверить, является ли длинная переменная нулевой, вы можете преобразовать это в Long и проверить,
How to check a Long for null in java
Primitive data types cannot be null . Only Object data types can be null .
There are 8 primitive types in Java:
| Data Type | Size | Description |
|---|---|---|
| byte | 1 byte | Int8 |
| short | 2 bytes | Int16 |
| int | 4 bytes | Int32 |
| long | 8 bytes | Int64 |
| float | 4 bytes | Single |
| double | 8 bytes | Double |
| boolean | 1 bit | Boolean |
If you use Long (wrapper class for long ) then you can check for null ‘s:
If it is Long object then You can use longValue == null or you can use Objects.isNull(longValue) method in Java 7+ projects .
Please check Objects for more info.
If the longValue variable is of type Long (the wrapper class, not the primitive long ), then yes you can check for null values.
A primitive variable needs to be initialized to some value explicitly (e.g. to 0 ) so its value will never be null.
You can check Long object for null value with longValue == null , you can use longValue == 0L for long (primitive), because default value of long is 0L, but it’s result will be true if longValue is zero too