Key Ideas
[Part 2 of 11]
Although there is a lot in this part, the key ideas are fairly simple. They are:
- That to make a primitive or object variable, you need to declare a label for it:
int a;
double b;
boolean c;
Point d;
String e;
- You then need to assign them some data, which, for an object, will be the more complicated code captured in a class:
a = 10;
b = 10.0;
c = true;
d = new Point();
e = "Some text";
- You can do both the declaration and assignment in one go:
int a = 10;
but either way, you only need to do the declarations once.
double b = 10.0;
boolean c = true;
Point d = new Point();
String e = "Some text";
- Once you have the variable set up, you can use it in three ways: you can
use it to get at the information inside, or you can use it to change the information the label is pointed at (including
null
, in the case of objects), or, with objects, you can use it to do the same things to the information it contains:
int f;
f = a; // Copy the value of 'a' into 'f'.
b = 10.0;
b = b + 1.0;
c = false;
f = d.x
d = new Point();
d = null;
d = someOtherPoint; // Make both the 'd' and 'someOtherPoint' labels stick to the same underlying object.
e = e + " " + "Some new text";
but either way, you only need to do the declarations once. - Constructing an array is just like making any variable,
but for the fact that you first assign spaces, then values in those
spaces. To get and set array values you use the array name and the
position of the space you want to change.
int[] intArray = new int[];
intArray[0] = 10;
System.out.println(intArray[0]);
Point[] objectArray = new Point[10];
objectArray[0] = new Point();
objectArray[1] = someExistingPoint;
System.out.println(objectArray[0].x);
Here's some code which uses these ideas:
public class Point {
double x = 100.0;
double y = 100.0;
}
public class PointUser {
public static void main (String args[]) {
double hereX = 200.0;
double hereY = 400.0;
String text = "ys = ";
Point herePoint = new Point();
hereX = herePoint.x;
herePoint.y = hereY;
System.out.println(text + hereY + " " + herePoint.y);
}
}