Variables
2. Introduction
Assignment statements and operators are fundamental to programming, enabling data manipulation and computation. Assignment statements store values in variables, while operators define the operations performed on data, such as arithmetic, comparison, or logical operations. This lecture explores their definitions, characteristics, use cases, and examples, with a focus on Java and comparisons to Python and C++.
1. Assignment Statements
Definition
An assignment statement assigns a value to a variable, typically using the assignment operator (=). It associates a variable name with a value or the result of an expression, storing it in memory for later use.
Characteristics
Syntax: variable = value; or variable = expression;
Components:
Variable: The named storage location (e.g., age, total).
Assignment Operator: Usually = (stores the right-hand side value in the left-hand side variable).
Value/Expression: A literal, variable, or computed result (e.g., 42, x + y).
Type Safety: In statically typed languages like Java, the value’s type must match the variable’s declared type.
Chaining: Some languages allow multiple assignments in one statement (e.g., x = y = 10;).
Side Effects: Assignment can modify a variable’s value, affecting program state.
Use Cases
Initializing variables (e.g., score = 0;).
Updating values based on calculations (e.g., total = price * quantity;).
Storing user input or intermediate results.