CS 121 - Chapter Two: Variables, Data and the For Loop
Overview
Focus on understanding variables, their declaration, and utilization within loops in programming. This chapter is foundational, ensuring a solid grasp of how data is stored and manipulated.
Emphasis on learning and reinforcing fundamentals in programming, providing the building blocks for more complex algorithms and data structures.
Variables
Definition: A piece of the computer's memory that is given a symbolic name (an identifier) and a specific data type, enabling it to store a particular kind of value (e.g., whole numbers, decimal numbers, text characters). Variables serve as containers for data that can change during the execution of a program.
Analogy: Compared to preset stations on a car stereo (each station stores a specific frequency) or speed dials on a cell phone (each button stores a specific phone number). Just as these presets hold a value that can be changed, a variable holds a value in memory.
Steps for Using a Variable:
Declare it: This step involves telling the compiler about the variable's name and its data type. This allocates the necessary memory space and prepares it for use.
Initialize it: This means assigning an initial value to the declared variable. It's crucial because an uninitialized variable can lead to unpredictable behavior or errors.
Use it: Once declared and initialized, the variable's stored value can be accessed, modified, or used in computations and output operations.
Declaration
Variable Declaration: This sets aside a specified amount of memory to store a value, based on the variable's data type. For example, an
inttypically reserves 4 bytes, while adoubletypically reserves 8 bytes.Must declare variables before use; attempting to use an undeclared variable will result in a compile-time error.
Syntax:
type name;wheretypespecifies the kind of data (e.g.,int,double,boolean,char,String) andnameis the identifier you choose for the variable, following naming conventions.Examples:
int x;// Declares an integer variable namedx.double myGPA;// Declares a double-precision floating-point variable namedmyGPA.
The name acts as an identifier, a unique label that allows you to refer to that specific memory location throughout your program.
Assignment
Definition: Assignment stores a value into a previously declared variable's memory location. It overwrites any previous value held by that variable.
The assigned value can be a direct literal value, another variable's value, or the result of an expression.
Syntax:
name = expression;The=symbol is the assignment operator, not an equality sign.Examples:
int x; x = 3;// Declaresxand then assigns the literal value 3 to it.double myGPA; myGPA = 1.0 + 2.25;// DeclaresmyGPAand assigns the result of the expression (1.0 + 2.25), which is 3.25, to it.
Using Variables
Once a variable is assigned a value, it can be utilized in various expressions, print statements, or as part of conditional logic. Variables make programs dynamic, allowing them to process and react to changing data.
Examples:
int x; x = 3; System.out.println("x is " + x);// Output:x is 3. The+operator here concatenates the string literal with the string representation ofx's value.System.out.println(5 * x - 1);// Withxas 3, this expression evaluates to (5 * 3) - 1 = 15 - 1 = 14. Output:14.
Variables can be reassigned multiple times during program execution, with each new assignment overwriting the previous value.
Example:
x = 3; System.out.println(x + " here");// Output:3 herex = 4 + 7; System.out.println("now x is " + x);//xis reassigned to 11. Output:now x is 11
Declaration/Initialization
A variable can be declared and initialized in a single statement, combining the first two steps of variable usage for convenience and often better readability.
Syntax:
type name = value;Examples:
double myGPA = 3.95;// DeclaresmyGPAas adoubleand immediately assigns it the value 3.95.int x = (11 % 3) + 12;// Declaresxas anintand assigns the result of the expression (11 \% 3) + 12, which is (2) + 12 = 14. Soxbecomes 14.
Assignment and Algebra
The assignment operator
=does not signify equality as in algebra (x = y implies $y$ equals $x$); instead, it means "evaluate the expression on the right-hand side and store its resulting value into the variable on the left-hand side."The right-side expression is always computed first, and only then is its result placed into the left-side variable.
Example:
int x = 3; x = x + 2;// First,xis 3. Then, the right side$x + 2$evaluates to 3 + 2 = 5. Finally, this value 5 is stored back intox. After this operation,xbecomes 5, not an algebraic contradiction.
Assignment and Types
A variable can only hold values that correspond to its declared data type. Storing an incompatible type will typically result in a compile-time error or a loss of precision.
Example of Type Mismatch Error:
int x = 2.5;// This will produce a compile-time error because2.5is adoubleliteral, which cannot be implicitly converted to anintwithout potential data loss.intvariables can only store whole numbers.Implicit Type Conversion (Widening Conversion): An
intvalue can be stored in adoublevariable, and it will be converted automatically and safely, asdoubleoffers greater precision and range.Examples of Implicit Conversion:
double myGPA = 4;//4(anint) is automatically converted to4.0(adouble) and stored inmyGPA.double avg = 11 / 2;// This is a common pitfall. The division$11 / 2$is performed using integer division first because both operands (11 and 2) are integers. Integer division truncates the decimal part, so$11 / 2$evaluates to 5. Thisintvalue 5 is then implicitly converted to5.0(adouble) and stored inavg. To get5.5, at least one of the operands must be a floating-point type:double avg = 11.0 / 2;ordouble avg = (double)11 / 2;.
Compiler Errors
Compiler (syntactic) errors are identified during the compilation phase of a program, before it runs. They prevent the program from being converted into executable code.
Errors arise from uninitialized variables or duplicate declarations.
Example of Uninitialized Variable Error:
int x; System.out.println(x);// Error:xhas not been initialized. The compiler flags this becausexhas no guaranteed value, leading to undefined behavior.Example of Duplicate Declaration Error: Declaring a variable with the same name and scope twice will cause a compile-time error:
int x; int x;// Error:xalready exists. Variables must have unique identifiers within their scope.int x = 3; int x = 5;// Error:xalready exists. Even if initialized, a variable cannot be declared twice in the same scope.
Printing a Variable's Value
To print a variable's value along with a string literal, use the
+operator. InSystem.out.println(), the+operator performs string concatenation when one of the operands is aString.Examples:
double grade = (95.1 + 71.9 + 82.6) / 3.0; System.out.println("Your grade was " + grade);// Output:Your grade was 83.2. Thegradevariable'sdoublevalue is converted to aStringand joined with the literal string.int students = 11 + 17 + 4 + 19 + 14; System.out.println("There are " + students + " students in the course.");// Output:There are 65 students in the course.. Thestudentsvariable (65) is converted to string and concatenated with the surrounding strings.
Expressions
Definition: An expression consists of a combination of values (literals, variables), operators (arithmetic, relational, logical), and method calls that computes to a single value. Every expression has a type (e.g.,
int,double,boolean) and can be evaluated.Examples of Expressions:
1 + 4 * 5// This expression evaluates to 21, following operator precedence (multiplication before addition).(7 + 2) * 6 / 3// This expression evaluates to (9) * 6 / 3 = 54 / 3 = 18. Parentheses dictate the order of operations.The simplest expression is a literal value (e.g.,
5,3.14,"hello"); complexities involve multiple operators, variables, and parentheses to control the order of evaluation (operator precedence and associativity).