A Tale of 4 Variables
description
Transcript of A Tale of 4 Variables
A Tale of 4 Variables
intX intY char c
double d
Once upon a time…
There was a program
And in that program there were methods A click method
And the main method
public void click()
public static void main()
And in the methods…There were variables
And the variables were declared
Creating space in memory to hold information
int intX;
int intY; intX
intY
public void click() {
But the variables were emptyThere was nobody home.
And different kinds of variables hold different kinds of information Are you happy?
That’s true or false boolean
What’s your middle initial? That’s a single letter char
How far away do you live? That’s a number, it could include a fraction or decimal double
And the assignment statementwas executed And it gave values to the variables
intX = 8; intY = 5;
intY
intX
8
5
Just be sure to declare the right kind of variable to hold the right kind of information
Which ones are correct types? int distance = 45.5;boolean happy = false;char initial = “Tom”;double distance = “far away”;char letterGrade = ‘A’;boolean b = “true”;
This is also called a floating point value, it has a decimal
point. An integer does
not.
Of course, assignment is not the same as equals intX = intX + 3;
The algebra teacher said
The computer teacher said
No number can equal itself plus 3
= means
Always do the equation on the
right first, then assign the
result to the variable on the left
So… intX = intX + 3
Means…First take the value of intXAdd 3Store the result in intX
intX
8
8 + 3
=11
intX
11
This is a literal value, it’s the same every time the program runs, intX is a variable, it can change
And the students were happy
Because they understood
And the students could assign values to variables They knew that after the assignment
statement intX = intY + intX * 2
intX =
intX
11
intY
5
intX
27
So whenever you want to remember information in a program Or if you want to leave a fill-in-the-blank
space to be filled in later (like a Mad Lib) Use a variable to store the information
intY
5
Rules for making up your own variable names: Must start with a letter Can use numbers, letters and underscores
(_) Cannot use a work that already has a
special meaning in Java like:mainvoidsystem
Which identifiers do NOT follow the rules for Java variables? length println happyCamper best friend ready?
good4u 2many tax_amount total! b45