// declare_vs_assign: David I. Schwartz 1/2000 public class declare_vs_assign { public static void main(String[] args) { // Declare a variable called s // Variable now has a memory location and type // but not necessarily a value String s; // Try the following code: // System.out.println("Testing before assign: " + s); // What happens? Using a variable before assigning makes Java upset. // Java produces an error, like: // declare_vs_assign.java:11: Variable s may not have been initialized. // System.out.println("Testing before assign: " + s); // 1 error // Currently, what does Java see as s? An empty location: // __s__ // | | <== no value inside s location // |___| <== Java expects a String to go there, though! // Now, assign the variable s // Store a value inside the variable by using assignment // Syntax: variable = value or expression // the left hand side (LHS) is variable // the right hand side (RHS) is a value or expression // Java treats the assignment as LHS <- RHS, // where LHS stores the value of RHS. // Note that Java must evaluate RHS before assigning it to LHS. s = "Hello, world!"; System.out.println("Testing1 after assign: " + s); // Currently, what does Java see as s? An filled location: // ______s_____ // | "Hello, | <== no value inside s location // | World!" | <== Java expects a String to go there, though! // |__________| // Demonstrate version with an expression in the RHS: s = "Hello," + " world!"; System.out.println("Testing2 after assign: " + s); } } /* Output: Testing1 after assign: Hello, world! Testing2 after assign: Hello, world! */