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
- no spaces, cant start with number
There are 2 types of variables:
- primitive - ints, doubles, boolean [there are others] - really
basic stuff
- non-primitive - OBJECTS - Strings, Square, Cars, Graphics
- have methods and properties that can be done to them:
- like g.drawLine(23,23,40,40) and 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 shorter
i++;
and if you wanted to decrease by 1 you could i--;
We cant say:
k=60.4;
Another example:
int j=15/2;
j would then be: 7 (not 7.5).
Doubles
-used to store real numbers, numbers with decimals;
like money: 75.67 or someones average 92.37
-to use, same as using an integer:
double studentAverage;
studentAverage=92.37;
or
double studentAverage=92.37;
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
}
|