国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java Javagetting Started Is null an object in java?

Is null an object in java?

Dec 06, 2019 pm 02:34 PM
java null object

Is null an object in java?

null in java is neither an object nor a type, it is just a special value, you can assign it to any reference type, you can also Convert null to any type.

Detailed explanation of null keyword

1. First of all, null is a keyword, like public, static, and final. It is case-sensitive, you cannot write null as Null or NULL, the compiler will not recognize them and report an error.

2. Just like every basic type has a default value, for example, the default value of int is 0, the default value of boolean is false, and null is the default value of any reference type. Just like you create a boolean variable that has false as its default value, any reference variable in Java has null as its default value. This is true for all variables.

Such as member variables, local variables, instance variables, static variables (when you use an uninitialized local variable, the compiler will warn you). To demonstrate this fact, you can observe this reference variable by creating a variable and then printing its value.

Free video tutorial recommendation: java video

3. We want to clarify some misunderstandings. null is neither an object nor a type, it is just a special Value, you can assign it to any reference type, you can also convert null to any type, look at the following code:

String str = null;
Integer i = null;
Double d = null; 

String myStr = (String) null;
Integer myI = (Integer) null;
Double myD = (Double) null;

You can see that during compilation and runtime, null is cast to any Reference types are all feasible and will not throw a null pointer exception at runtime.

4. Null can be assigned to reference variables, but you cannot assign null to basic type variables, such as int, double, float, and boolean. The compiler will report an error.

As you can see, when you assign null directly to a basic type, a compilation error will occur. But if you assign null to the wrapper class object, and then assign object to the respective basic types, the compiler will not report it, but you will encounter a null pointer exception at runtime. This is caused by automatic unboxing in Java.

5. Any wrapper class containing a null value will throw a null pointer exception when Java unboxes and generates basic data types. Some programmers make the mistake of thinking that autoboxing will convert null to the default value of the respective basic type, such as 0 for int and false for boolean type, but that is not correct, as shown below:

Integer iAmNull = null;
int i = iAmNull; // Remember - No Compilation Error

But when you run the above code snippet, you will see on the console that the main thread throws a null pointer exception. Many such errors occur when using HashMap and Integer key values. An error will appear when you run the following code.

public class Test3 {
  public static void main(String args[]) throws InterruptedException {
    Map numberAndCount = new HashMap<>();
    int[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};
    for(int i : numbers){      
  int count = (int) numberAndCount.get(i);//NullPointerException
      numberAndCount.put(i, count++); 
    } 
  }
}
package test;import java.util.HashMap;
import java.util.Map;
public class Test3 {
  public static void main(String args[]) throws InterruptedException {    
      Map numberAndCount = new HashMap<>();    
      Integer[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};    
      for(Integer i : numbers){      
          Integer count = (Integer) numberAndCount.get(i);      
          numberAndCount.put(i, count++); // NullPointerException    
      }    
  }
}

This code looks very simple and error-free. All you do is find how many times a number appears in an array, which is the typical technique for finding duplicates in Java arrays. The developer first gets the previous value, then adds one, and finally puts the value back into the Map.

Programmers may think that when calling the put method, the first way is to convert int to report a null pointer, verify what was said before. In the second way, autoboxing will handle the unboxing problem by itself, but it forgets that when a number has no count value, the get method returns null instead of 0, because the default value of Integer is null instead of 0. Autoboxing will return a NullPointerException when passing a null value to an int variable.

6. If a reference type variable with a null value is used, the instanceof operation will return false

Integer iAmNull = null;
if(iAmNull instanceof Integer){
   System.out.println("iAmNull is instance of Integer");                            
 }else{
   System.out.println("iAmNull is NOT an instance of Integer");
}

This is a very important feature of the instanceof operation, making it very easy to check the type cast. it works.

7. You may know that you cannot call non-static methods to use a reference type variable with a null value. It will throw a null pointer exception, but you may not know that you can use static methods to use a reference type variable with a null value. Because static methods use static binding, null pointer exceptions will not be thrown. The following is an example:

public class Testing {            
   public static void main(String args[]){
      Testing myObject = null;
      myObject.iAmStaticMethod();
      myObject.iAmNonStaticMethod();                            
   }
  
   private static void iAmStaticMethod(){
        System.out.println("I am static method, can be called by null reference");
   }
  
   private void iAmNonStaticMethod(){
       System.out.println("I am NON static method, don&#39;t date to call me by null");
   }

8. You can pass null to the method. At this time, the method can receive any reference type, for example public void print(Object obj)You can call print like this (null). This is OK from a compilation perspective, but the result depends entirely on the method. Null-safe methods, like the print method in this example, do not throw a NullPointerException and simply exit gracefully.

If the business logic allows it, it is recommended to use the null safe method.

9. You can use == or != operations to compare null values, but you cannot use other algorithms or logical operations, such as less than or greater than. In Java null==null will return true.

Recommended related articles and tutorials: Getting started with java

The above is the detailed content of Is null an object in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles