General info:::

command prompt actions (default windows intepreter):

Compile:   javac

                -or-  x:folder1\folder2\javac

Run:   java nameofcode

                see -or- above

Change directory:  cd x:folder1\folder2\

                when changing drives, you may need to enter an x: return at the next prompt.



If you’re getting type/identifier errors, you probably forgot the public static void main(String args[]) { ... } clause.




^rules for variable names:

It must be a legal Java identifier comprised of a series of Unicode characters. Unicode is a character-coding system designed to support text written in diverse human languages. It allows for the codification of up to 65,536 characters, currently 34,168 have been assigned. This allows you to use characters in your Java programs from various alphabets, such as Japanese, Greek, Cyrillic, and Hebrew. This is important so that programmers can write code that is meaningful in their native languages.

It must not be a keyword(in the Learning the Java Language trail), a boolean literal (true or false), or the reserved word null.

It must be unique within its scope.


...standard multi-word capsing dictates to start with a lowercase letter and caps 1st char of 2+nd words.



^Scope: see for a great pictoral.

4 scopes:  member var, local var, method param, exception-handler param.

class TheClass


member var declarations

...               <--member var scope

public void aMethod(method parameters)


...         <--method param scope

local variable declarations

...         <--local scope

catch(exception handler parameters)


...         <-- exception handler scope





^member vars can be declared anywhere in the class except the method and can be used anywhere.

^locals vars exist only in the method.

^method params are used to pass values into methods.


^type of var called “final” cannot be changed once initialized.  to define:

                final int aFinalVar=0;


                final int aFinalVar;



                (in the method the variable is called a “blank final”)






^variable type chart:



Byte-length integer

8-bit two's complement


Short integer

16-bit two's complement



32-bit two's complement


Long integer

64-bit two's complement

(real numbers)


Single-precision floating point

32-bit IEEE 754


Double-precision floating point

64-bit IEEE 754

(other types)


A single character

16-bit Unicode character


A boolean value (true or false)

true or false





An object is an instance of a class.

to create an object, you instantiate a class:

Rectangle rect = new Rectangle();

creates a variable rect from a previously defined class Rectangle.  new is an operator in java which creates/allocates space for a new object.  rectange() calls the rectangle’s constructor, which initializes the object.

<all this is at>


^how to change the state of an object:

-directly edit the objects variables (discouraged, against “true” OO ideals)

-edit the object’s state through one of its methods.

^^to edit the object directly, using our rectangle example:

(changing the origin, or position...)

rect.origin = new Point(15, 37);

::use the format


objectReference canb e the object’s name, or any method which returns an object name.


height = new Rectangle().height;

creates a variable which ultimately gets the default height of a Rectangle object...and throws the object away since we didn’t set an object name for it. but that’s okay, we just wanted the default value.

^^to edit the object through a method...


should do the trick no problem.

::use the format





int areaOfRectangle= new Rectangle(100,50).area();

will return the default area of a rectangle.




Java has a useful process called garbage collection.  Basically, it deletes any object for which there are no more references.  This is useful, since in most other OO languages you must explicitly delete unused objects, which is tedious and eats memory.  An  object is auotmatically dropped whin its variable goes out of scope, or you can explicitly delete it by setting its reference to null.  after being garbage-collected, java gives the variable the chance to clean up after itself through a call to the finalize method.... in certain situations, it is required that a programmer call this method in order to free up native peers and other things inaccesible to the collector. finalize is a member of the Object class, which is at the top of the heirarchy and parent of everything.  if you override finalize, be sure to call super.finalize as the last thing it does.



^Class  creation: example is a last-in-first-out stack.




Vector is a growable array of objects and does a nice job of allocating space for new objects as space is required. The Stack class makes use of this code by using a Vector to store its elements. However, it imposes LIFO restrictions on the Vector-- that is, you can only add elements to and remove elements from the top of the stack.

class declaration:

public<publicly accessible> abstract<cannot be instantiated> final<cannot be subclassed> class NameOfClass extends Super<superclass of class> implements Interfaces<interfaces implemented by class>{




the constructor has the same name as the class.  you can have as many constructors as you want, FI

public Stack() {
    items = new Vector(10);
public Stack(int initialSize) {
    items = new Vector(initialSize);

...note they both have the same name.  java will pick which one depending on the info you give it when you call the constructor.  however, you don’t need to provide a constructor... java has a default asigned to each class you create.




unary(++), binary(/), ternary(?:)

?: is shorthand if-else statement

 unaries support either prefix (++1) or postfix(1++) notation.

binarys operators suppors infix notation(1+2)

the ternary(?: is the only one) operator also supports infix notation:

                !x ? y=x : y=(x-2)

                (if x != 1 set y=x, other wise set y= (x-2))

an operation evaluates to its result...

in java, you can use the + operator not only to add numbers but to concatenate strings as well.

new unary funciton:

(op)         (use)        (desc)

+              +op         promotes op to int if it’s a byte, short or char.


increment/decrement fixes:

(op)         (use)        (desc)

++           op++       increments by 1, evaluates to the value of op before increment

++           ++op       increments by 1, evaluates to the value of op after increment

--             op--         decrements by 1, evaluates to the value of op before increment

--             --op         decrements by 1, evaluates to the value of op after increment.


fI, in:

for(int i=arrayOfINts.length; --i>=0;){



 the last iteration of the loop occurs when i=0.  i is decremented for each iteration.


other differences/new stuff:

(op)         (use)                        (desc: returns true if...)

&&          op1&&op2             op1 and op2 are true, evals op2 first.  only evals op1 if op2 is true.

||               op1||op2                  op1 or op2 is true, evals op2 first

!               !op                          op is false

&             op1&op2                                op1 and op2 are true, evals both ops always.  both must be boolean.

|               op1|op2                   see &&/& relation.

^              op1^op2                 if only one op is true but not both.... XOR


shift/logical operators:

(op)         (use)                        (operation)

>>           op1>>op2               shifts bits of op1 right by distance op2

<<           op1<<op2               shifts bits of op1 left by distance op2

>>>                                         same, but unsigned.




the binary representation of 13 is 1101. shifted right one bit leaves 110, or 6.

 bitwise logical ops:

(op)         (use)        (desc)

&                             bitwise and

|                               bitwise or

^                              bitwise xor

~              ~op2        bitwise complement


bitwise & results:

(op1)       (op2)       (res)

0              0              0

0              1              0

1              0              0

1              1              1




gives 12:::








or 12.


inclusive(|) results:

0              0              0

0              1              1

1              0              1

1              1              1


exclusive(^) results:

0              0              0

0              1              1

1              0              1

1              1              0


the complement(~) inverses the bits of the number...



 an example ( follows:


Among other things, bitwise manipulations are useful for managing sets of boolean flags. Suppose for example, that you had several boolean flags in your program that indicated the state of various components in your program: is it visible, is it draggable, and so on. Rather than define a separate boolean variable to hold each flag, you could define a single variable, flags, for all of them. Each bit within flags would represent the current state of one of the flags. You would then use bit manipulations to set and get each flag.

First, set up constants that indicated the various flags for your program. These flags should each be a different power of two to ensure that the "on" bit doesn't overlap with another flag. Define a variable, flags, whose bits would be set according to the current state of each flag. The following code sample initializes flags to 0 which means that all flags are false (none of the bits are set).

static final int VISIBLE = 1;

static final int DRAGGABLE = 2;

static final int SELECTABLE = 4;

static final int EDITABLE = 8;


int flags = 0;

To set the "visible" flag when something became visible you would use this statement:

flags = flags | VISIBLE;

To test for visibility, you could then write:

if ((flags & VISIBLE) == VISIBLE) {




^Assignment Operators:

+=           -=            *=            /=             %=

&=           |=             ^=            <<=         >>=         >>>=


all uses follow:

(use)                        (expanded)

op1 op=  op2                          op1= op1 op op2



^Control Flow Statements:

Statement Type



while, do-while , for

decision making

if-else, switch-case

exception handling

try-catch-finally, throw


break, continue, label:, return






//evaluates expression, and if true, executes statement, evaluates expression..


do {


} while (expression);

//executes statement, evaluates expression, (if true) executes statement...


for (initialization ; termination ; increment )  {



//initializes an increment variable, evaluates termination to go on, executes

statement, executes increment, evaluates termination...


if(expression1)  {


}  else  if(expression2) {


}  else  {




switch (integer expression) {

    case integer expression:








//case #s match values of the variable named in opening the statement.

      forgetting the “break;” will result in a fall-through(which should be




Exception handling statements lessons are down...


Another form of the break statement causes flow of control to break out of a labeled statement. You label a statement by placing a legal Java identifier (the label) followed by a colon (:) before the statement:

statementName: someJavaStatement

To break out of the statement labeled statementName use the following form of the break statement.

break statementName;

Labeled breaks are an alternative to the goto statement, which is not supported by the Java language.


continue (unlabeled) skips the rest of your statements in a loop to execute the next one.


The labeled form of the continue statement continues at the next iteration of the labeled loop. Consider this implementation of the String class's indexOf method which uses the labeled form of continue:


public int indexOf(String str, int fromIndex) {

    char[] v1 = value;

    char[] v2 = str.value;

    int max = offset + (count - str.count);


    for (int i = offset + ((fromIndex < 0) ? 0 : fromIndex);

         i <= max ; i++)


        int n = str.count;

        int j = i;

        int k = str.offset;

        while (n-- != 0) {

            if (v1[j++] != v2[k++]) {

                continue test;



        return i - offset;


    return -1;



the return statement is standard; use just “return;”(with no following value) if the method’s type is void.



^Declaring Member Variables


private Vector items;



accessLevel  lets you define which classes have access to the variable

static  declares teh var as a class var rather thatn an instance var... used in declaring class methods.

final  unchangeable var once initialized.

transient   used in object serialization to mark objects which should not be serialized.

volitile   used to prevent the compiler from performing certain optimizations on a member...advanced

type   int, float, boolean, etc

name  obv...reference; begin with lowercase is standard


^ Method Implementation  :

two parts: declaration; body.  declaration defined all the methods attributes:

                public Object push(Object item)

(access level; return type; method name; arguments)

minimum requirements:

returnType methodName()  {




more details...


abstract:  has no implementation; must be a member of an abstract class.

native:  lets you use prev-written libraries written in other languages(like C)

synchronized:   ensures that concurrently running threads access info in a thread-safe manner.

[throws exceptions]   required if your method throws any checked exceptions.


if you return an object from amethod, the class of the returned object must be either a subclass of or the exact class of the return type.


Java supports method name overloading so that multiple methods can share the same name. For example, suppose you are writing a class that can render various types of data (strings, integers, and so on) to its drawing area. You need to write a method that knows how to render each data type. In other languages, you have to think of a new name for each method, for example, drawString, drawInteger, drawFloat, and so on. In Java, you can use the same name for all of the drawing methods but pass a different type of parameter to each method. So, in your data rendering class, you can declare three methods named draw, each of which takes a different type of parameter:

class DataRenderer {

    void draw(String s) {

        . . .


    void draw(int i) {

        . . .


    void draw(float f) {

        . . .






Typically, within an object's method body you can just refer directly to the object's member variables. However, sometimes you need to disambiguate the member variable name if one of the arguments to the method has the same name.

For example, the following constructor for the HSBColor class initializes some of an object's member variables according to the arguments passed into the constructor. Each argument to the constructor has the same name as the object's member variable whose initial value the argument contains.

class HSBColor {

    int hue, saturation, brightness;

    HSBColor (int hue, int saturation, int brightness) {

        this.hue = hue;

        this.saturation = saturation;

        this.brightness = brightness;


You must use this in this constructor because you have to disambiguate the argument hue from the member variable hue (and so on with the other arguments). Writing hue = hue; makes no sense. Argument names take precedence and hide member variables with the same name. So to refer to the member variable you must do so through the current object--this--explicitly.





^arrays and strings

to declare an array, use this format:

elementType[] arrayName = new elementType[arraySize]


                int[] myInt=new int[10];


...sample code section:

int[] myInt=new int[10];

for(j=0; j<myInt.length; j++) {


                System.out.println(“[j]= “+myInt[j]);



a string type object:


as in:

String[] arrayOfStrings = new String[10];

allocates an array of ten pointers-to-strings.  the memory is allocated to the pointers, but not the strings, so to use the positions in the array you must

for(int i=0; i<arrayOfStrings.length; i++)  {

                arrayOfStrings[i]=new String(“Hello “+i);  //(FI)












left off...







basic Hello, world script:



 * The HelloWorldApp class implements an application that

 * simply displays "Hello World!" to the standard output.


class HelloWorldApp {

    public static void main(String[] args) {

        System.out.println("Hello World!");   //Display the string.








*bubble sort from an array


public class Sort {
    public static void main(String[] args) {
        int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
                              2000, 8, 622, 127 };
        for (int i = arrayOfInts.length; --i >= 0; ) {
            for (int j = 0; j < i; j++) {
                if (arrayOfInts[j] > arrayOfInts[j+1]) {
                    int temp = arrayOfInts[j];
                    arrayOfInts[j] = arrayOfInts[j+1];
                    arrayOfInts[j+1] = temp;
        for (int i = 0; i < arrayOfInts.length; i++) {
            System.out.print(arrayOfInts[i] + " ");





*max values of variables


public class MaxVariables {
    public static void main(String args[]) {
        // integers
        byte largestByte = Byte.MAX_VALUE;
        short largestShort = Short.MAX_VALUE;
        int largestInteger = Integer.MAX_VALUE;
        long largestLong = Long.MAX_VALUE;
        // real numbers
        float largestFloat = Float.MAX_VALUE;
        double largestDouble = Double.MAX_VALUE;
        // other primitive types
        char aChar = 'S';
        boolean aBoolean = true;
        // display them all
        System.out.println("The largest byte value is " + largestByte);
        System.out.println("The largest short value is " + largestShort);
        System.out.println("The largest integer value is " + largestInteger);
        System.out.println("The largest long value is " + largestLong);
        System.out.println("The largest float value is " + largestFloat);
        System.out.println("The largest double value is " + largestDouble);
        if (Character.isUpperCase(aChar)) {
            System.out.println("The character " + aChar + " is upper case.");
        } else {
            System.out.println("The character " + aChar + " is lower case.");
        System.out.println("The value of aBoolean is " + aBoolean);