VarDemo.java

Download VarDemo.java

 1: import java.io.*;
 2: import java.net.*;
 3: import java.util.*;
 4: 
 5: /**
 6:  *  Demo of declaring and initializing variables.  The new "var"
 7:  *  syntax comes with several restrictions, as shown below.  It is
 8:  *  claimed that using var when legal makes code more readable.  You
 9:  *  be the judge!
10:  *  Written 2024 by Wayne Pollock.
11:  */
12: public class VarDemo {
13:     /**  Exception handling omitted for clarity of the example. */
14:     public static void main ( String[] args ) throws Exception {
15:         //  Six regular declarations with initializers:
16:         int num = 10;
17:         String name = "Hymie";
18:         URL wpollock = new URI("https://wpollock.com/").toURL();
19:         BufferedReader reader = new BufferedReader( new FileReader("data.txt"));
20:         ArrayList<String> rooster = new ArrayList<>();
21:         int[] array = new int[4];
22: 
23:         // Rewritten to use "var":
24:         var num2 = 10;
25:         var name2 = "Hymie";
26:         var wpollock2 = new URI("https://wpollock.com/").toURL();
27:         var reader2 = new BufferedReader( new FileReader("data.txt"));
28:         var rooster2 = new ArrayList<String>();
29:         var array2 = new int[4];
30: 
31:         // None of the following are legal; See
32:         // docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-14.4-400-A
33:         // for the exact rules:
34: /*
35:         foo = "foo";  // no var keyword
36:         var foo;  // no initial value
37:         var nums = {1, 2, 3};  // Array initializer cannot use var
38:         var appendSpace = a -> a + " ";  // A "Lambda" cannot use var
39:         var compareString = String::compareTo;  // A method reference cannot use var
40:         var b = 2, c = 3;   // Illegal: multiple declarators cannot use var
41:         var array3[] = new int[4]; // Illegal: extra bracket pair after "3"
42:         var n = null;
43: */
44:     }
45: }