The int
type in Java cannot be null. int
is the basic data type in Java, its default value is 0, and it cannot be assigned as null. Other basic data types (such as float
, double
, etc.) also follow the same rules.
Unlike basic data types, objects in Java can be null. There is no concept of null reference for basic data types.
Example: Trying to assign null to an int variable will cause an error
The following code will throw a compile-time error:
int myInt = null;
How to assign null values to integer variables?
If you need a variable that can represent a null value, you can use the Integer
class. Integer
is a wrapper class for int
, which is an object that can hold null values.
Example: Use the Integer class to store null values
public class Main { public static void main(String[] args) { Integer intVar = null; // Integer对象可以为null if (intVar == null) { System.out.println("intVar is null"); } else { System.out.println("intVar value: " + intVar); } } }
Output result:
<code>intVar is null</code>
The above is the detailed content of Can an int be null in Java?. For more information, please follow other related articles on the PHP Chinese website!