|
Variables
Just like in math, variables are used to represent other things
- numbers (integers, doubles, floats), text (characters, strings)
and things (ie dogs by a dog class)
Remember
- We use camel case (with first lowercase) for variables that
change; timeOfDay
- name things appropriately; for example studentAverage is much
better than sA or s
There are 2 types of variables:
- primitive - ints, doubles, char, boolean [there are others]
- non-primitive - OBJECTS - Strings, Square, Cars, Graphics
- have methods and properties that can be done to them:
- like stringName.length() or square1.makeVisible() or
bunny.move(50,frog);
Primitive Types
Integers (whole numbers
+ and -)
- to declare a integer k and set its value as 50, we say
int k;
k=50;
or
int k=50;
Now k has the value of 50;
Or if we wanted to add 30 to what k was:
k = k + 30;
If we wanted to add 1 to the value of i, we could
i=i+1;
or more concisely
i++;
and if you wanted to decrease by 1 you could i--;
If we said
k=60.4;
We'll we declared k as an int, so k actually would lose the .4,
and just be 60 - this is bad news.
Another example:
int j=15/2;
j would then be: 7 (not 7.5).
Doubles
-used to store real numbers, numbers with decimals;
$75.67 or someones average 92.37
-to use, same as using an integer:
double studentAverage;
studentAverage=92.37;
or
double studentAverage=92.37;
char
Chars are used to represent one letter only. Case matters, as always
in java. You put ' ' around the character to set it.
for example:
char myLetter = 'a';
Boolean
Booleans are variables that represent simply true or false. They
can be very useful when all you want is a variable to be on or off,
(true or false). The values true or false are not in quotation marks.
boolean firstTime = true;
// the code below will be executed if firsttime is true
// note it is not necessary to say firstTime ==true, although it will not give an error
// if we wanted to do an if statment if it was false, we could say if (!firstTime)
if (firstTime)
{
do this
}
|