Variables & Assignment
Variables & Assignment
- Variables refer to memory locations
for storing information.
- A variable:
- has a name
- has a type (examples:
int
,
float
or double
,
String
)
- has a value, which is stored in a specific location of a
specific size (the programmer generally doesn't have to know the
location or the size)
- The value of a variable may vary as a program runs.
- We set or change the value of a variable using assignment.
- Assignment is right to left — the variable name goes on the
left-hand side of the
=
symbol and the value (or calculation
that creates a value) goes on the right. You could think of
sum = a + b;
as really meaning
sum <-- a + b;
Example #1
int value1; // Create an integer variable
value1 = 2; // Initialize its value to 2
int value2 = 8; // Create a variable initialized to 8
int sum1 = value1 + value2; // Set a variable to a calculated value
System.out.println(value1 + ", " + value2 + ", " + sum1);
Output:
2, 8, 10
Example #2
double pi = 3.14159;
double sum2 = pi + value2; // int value2 will be temporarily "upgraded" to a double
System.out.println(pi + ", " + value2 + ", " + sum2);
Output:
3.14159, 8, 11.14159
Example #3
String word1 = "Hello";
String word2 = "world";
String greeting = word1 + " " + word2 + "!";
System.out.println(word1 + "\n" + word2 + "\n" + greeting);
greeting = word1 + " all!";
System.out.println(greeting);
Output:
Hello
world
Hello world!
Hello all!
Example #4
double x = 5;
double y = 10;
double sum = x + y;
double avg = sum / 2.0;
System.out.println("x + y = " + sum + "; avg = " + avg);
x = 32;
y = 10;
sum = x + y;
avg = sum / 2.0;
System.out.println("x + y = " + sum + "; avg = " + avg);
Output:
x + y = 15; avg = 7.5
x + y = 42; avg = 21
Alyce Brady, Kalamazoo College