Variable Values SEC T ION 4.2 How beneficial is using constants in a Java program? A fter the data items for a program have been identified, meaningful names assigned, and the appropriate data types declared, values need to be stored in variables. Java provides several ways for storing values in data items. One way is to assign a value directly by entering a textual version of the value. This is useful for some data, especially if the data value does not change from one execution of program to the next. When using this method, if the data value needs to change, the code would need to be edited and recompiled to take advantage of the new value. A second method is to ask the user to input a value. In this case, the user will enter a value using the keyboard or other input device and that value is assigned to the variable. This makes for more flexible execution of pro- grams. Each execution of the program can process new input values without needing to recompile. Learning Goals After completing this section, you will be able to: • Assign a literal value to a variable. • Set up proper constants. • Obtain input from the user. Terms call concatenation operator constant exception hard-coding literal value prompt String literal Assigning Values Once an identifier is defined for a variable, the programmer must provide values for that variable. Numbers, single characters, or strings can be provided. A constant value can be defined that will remain the same for the entire program or input can be obtained from the user. Java will convert the values to binary to store in memory. Therefore, there are rules for describing the input to Java. Assigning Literal Values A literal value is simply a textual representation of a value. To assign a value directly to a variable, Java provides the assignment operator, which is the equals sign (=). The equals sign should be familiar from creating initializations in math class, such as let x = 6. In a Java assignment statement, the target variable is given first, then the equals sign, then the value to be assigned. Thus, the assignment statement works from right to left. The Java syntax is: targetVariable = value // assign value to targetVariable Variable definitions and assignments are statements, so they must end with a semicolon. The data type and value can be combined in the same statement, if FYI Take care: assignment is different from an equation in algebra. It is not a statement of equality. It is an active storage of information in the program. Copyright Goodheart-Willcox Co., Inc. Copyright Goodheart-Willcox Co., Inc. 82 Introduction to Computer Science: Java Programming