我们知道null在每种语言中都是重要的概念,不仅在Java中,在这里我们还将研究有关null的各种因素。
null是一个非常关键的因素,这意味着我们在使用null时需要集中精力。
null是Java中的关键字,它与NullPointerException相关,而NullPointerException是java.lang包中的一个包,例如java.lang.NullPointerException。
如果在Java中执行带或不带null的操作,我们将看到NullPointerException抛出。
通常,我们将讨论一些情况,下面给出了这些情况...
情况1:我们知道null是区分大小写的
在这里,我们将看到为什么null在Java中是区分大小写的,而null在Java中是一个关键字,这就是为什么null在Java中是区分大小写的原因,因为java中的所有关键字都区分大小写。
注意:
区分大小写意味着用小写字母和大写字母表示的单词具有不同的含义,例如:null,NULL(两者都不同)。
在Java中(null)是有效的,但是如果我们写(NULL,0,Null)等,则这些单词无效,没有任何意义。
示例
class NullCaseSensitive{ public static void main(String[] args) throws Exception{ /*We are assigning null in str1 and it will execute without any error*/ String str1 = null; System.out.println("The value of str1 is "+str1); /* 我们在str2中分配Null,在str3中分配NULL 它将给出编译时错误,因为 Null和NULL在Java中无效 */ /* String str2 = Null; System.out.println("The value of str2 is "+str2); String str3 = NULL; System.out.println("The value of str3 is "+str3); */ } }
输出结果
E:\Programs>javac NullCaseSensitive.java E:\Programs>java NullCaseSensitive The value of str1 is null
情况2:我们知道Reference变量默认为null
在Java中,默认情况下,Integer引用变量在对象实例化时保留null值,换句话说,如果我们在对象实例化时未从末端分配任何值,则默认为null。
在Java中,如果在对象实例化开始时不分配任何其他值,则在对象实例化时String引用默认情况下为null。
在Java中,如果在对象实例化开始时不分配其他任何值,则对象实例化时对象引用默认为null。
示例
class ReferenceVariable { //声明引用变量 String str; Object obj; Integer in ; } class Main { public static void main(String[] args) throws Exception { ReferenceVariable rv = new ReferenceVariable(); System.out.println("The default value of the Object reference is " + rv.obj); System.out.println("The default value of the String reference is " + rv.str); System.out.println("The default value of the Integer reference is " + rv.in); } }
输出结果
The default value of the Object reference is null The default value of the String reference is null The default value of the Integer reference is null
情况3:如果将null赋给原始数据类型,则将获得编译时错误
示例
class AssignNullToPrimitive { public static void main(String[] args) { char ch = null; int i = null; /* We will get error here because we can'’'t null to primitive datatype*/ System.out.println("The value of the char is " + ch); System.out.println("The value of the int is " + i); } }
输出结果
E:\Programs>javac AssignNullToPrimitive.java AssignNullToPrimitive.java:5: error: incompatible types char ch = null; ^ required: char found: <null> AssignNullToPrimitive.java:6: error: incompatible types int i = null; ^ required: int found: <null> 2 errors
情况4:如果我们检查对象是否是类,接口等的实例,则如果对象不是null的实例(即表达式的值不为null),则返回true,否则返回false
示例
class CheckObjectInstanceOf { public static void main(String[] args) throws Exception { String str = null; Double d = null; Float f = 10.0f; System.out.println("Is str is an instanceof String " + (str instanceof String)); System.out.println("Is f is an instanceof Float " + (f instanceof Float)); System.out.println("Is d is an instanceof Double " + (d instanceof Double)); } }
输出结果
Is str is an instanceof String false Is f is an instanceof Float true Is d is an instanceof Double false