Home >Java >javaTutorial >Can an int be null in Java?

Can an int be null in Java?

Patricia Arquette
Patricia ArquetteOriginal
2025-02-07 11:48:15595browse

Can an int be null in Java?

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:

<code class="language-java">int myInt = null; </code>

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

<code class="language-java">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);
    }
  }
}</code>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn