Java Programming
CIS279
Tori Basford
tori@bly.net
Assignment(s):
None
Exercise(s):
See handout (Exercise 2: Arguments & Strings)
Quiz 1: Java Basics
Standard formatting:
All keywords are lower case. (ex. if, for, else, while, do)
All variable and function names start with lower case. (ex. total, itemCost, studentRecord)
All primary datatypes are lower case. (ex. byte, short, int, long, float, double, char, boolean)
(/p>
Classes:
A class is a factory that can create objects when commanded by the new operater.
for example:
The class PimaStudent can create PimaStudent, each of which contains a name field and an age field.
PimaStudent S1,S2,S3;
S1 = new PimaStudent();
In this case, S1 contains a "reference number" that points to where in memory the data for S1 is.
So, Java only works with either numbers that fit in a register or with refernce numbers that point to a refence in memory. However, unlike C, Java automatically deals with the data and NOT the pointer.
Variables:
Every variable MUST be initialized. If a variable is not initialized, the program WILL NOT compile.
example:
int n;
int r=5;
if (r<3) {
    n=12;
} if (r<3) {
    n=0;
}
The above program will NOT compile and will generate an error of "n may be not be initalized." This happens because n will not be set to anything if r=3.
Null:
If a reference variable (not 8 primary types) contains the special value null, it doesn't point to any object.
examples:
s2 = null;
s1.age = 25;     <-  Go to object, select the age field, and store 25 in it
s1.name = "Tom";
System.out.println(s1.age);
s2.age = 12;     <-  null pointer exception error.
If s2 contains null, there are only 3 things you can do with it:
Arguments, Arrays, and Strings:
If we type "jr P1", Java looks inside that class for the method main() and sends it an array containing 0 strings. If we type "jr P1 cat mouse" then Java calls main() as before and sends 2 strings.
An array is an object. Every array object contains an int field called 'length' which contains how many items are in the array.
example:
System.out.println("The number of strings is " + args.length);
A string is an object. Every string object contains some methods.
Accessing Data fields:
If you know the names of the fields and they are not private, you can do anything you want with them.
examples:
SX.name = "tony";
SX.age = 56;
Sometimes the fields are private or you don't know their names, but the object provides "accessor" methods. For example, PimaStudent has getAge(), getName(), setAge(), and setName().
examples:
SX.setname("tony");
System.out.println(SX.getName());
Sometimes the object contains constructors that store all the data for you.
examples:
SX = new PimaStudent("Tony", 25);
Frames:
This is an example of frames, using the old AWT toolkit.
| import java.awt.*;
public class Frames {     public static void main(String[]args){         Frame jf;         jf = new Frame();         jf.setSize(300,300);         jf.show();     } } |