-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNullDemo.java
More file actions
49 lines (35 loc) · 1.15 KB
/
NullDemo.java
File metadata and controls
49 lines (35 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class NullDemo
{
public static void main (String[] args)
{
String name;
// these would cause compiler errors:
// System.out.println (name);
// System.out.println (name.length());
// System.out.println (name.charAt(0));
/////////////////////////////////////////////////////////////////////
String x = null;
// this is valid:
System.out.println ("the value of x is: " + x);
// these would cause run-time errors...
// specifically, they would throw "NullPointerException":
// System.out.println (x.length());
// System.out.println (x.charAt(0));
/////////////////////////////////////////////////////////////////////
String[] a = new String[1];
// this is valid:
System.out.println ("The array is displayed here: " + a[0]);
// but this would throw a NullPointerException
// int len = a[0].length();
/////////////////////////////////////////////////////////////////////
String k=null;
if(k==null)
{
System.out.println ("k does not yet have a real value.");
}
else
{
System.out.println ("the value of k is " + k);
}
}
}