Java Keywords   
Peter Komisar      
©          Conestoga College     latest version 5.4 / 2008



The Dilemna Learning Java Keywords

We left the survey of Java Keywords until half way into
the course where it is hoped that the coverage will also
serve as mid-term review. When this lecture was delivered
earlier in the course it was always daunting as there was
so much in the keywords that involved explaining object-
oriented programming generally.

While a tour of the keywords is a mini-course in Java
all by itself, keep in mind we are just trying to create a
set of definitions for the Java keywords.

// All the references to the C programming language
// are
just for interest and for those who come from a
// C background.
They can safely be ignored

Following is a table that shows the keywords in a single
take.


Keyword Organization

Breakdown of Java Keyword Based on Category
 
 primitives  modifiers  control   exceptions  object oriented
boolean  private  if  try   class
 byte  protected  else  catch   new
 short  public   for   finally   extends
 int  static   do   throw  implements
 long  abstract  while  throws  interface
 float  final   switch   .  this
 double synchronized  case   .  super
 char  native  default  // in methods  instanceof
 enum // new JDK 1.5.  transient  break  return   import
 strictfp  volatile   continue  void  package
 Words reserved for values  true  false  null
 Words reserved to keep them out of action  goto  const  .
 Reserved words that have been dropped   widefp

 Reserved word recently added
 asserts


// strictfp has moved from reserved status to the keywords list
 

Keyword Organization

In the above table the keywords are separated based,
on the what role they play in the
Java language.

Primitives - First there are the primitives. They are mostly
storage types for number
values. There is also 'boolean'
which stores true and false, and 'char' that stores the
Unicode
types we discussed earlier.

Modifiers - The modifier keywords are placed beside an
identifier
to extend the definition of the identifiers type in
some way, almost like adjectives in a spoken language.

Control Keywords The control keywords offer the
means to control the logical path a Java program takes.

Exception Keywords - The exception keywords are like
control keywords in that they effect flow control however
they are specialized for
handling exceptions in a standard
manner.

Object-Oriented Keywords
- The object-oriented keywords
relate in some
way to the object oriented model Java uses.

Reserved Values - There are keywords which are referred
to
as reserved values, 'true', 'false' and 'null'. They form
their own category.

Reserved Keywords - There are keywords that have been
reserved to keep them out of action such as 'const' and
'goto'.

Method Keywords - The return and void keywords are
used in methods.

Miscellaneous - The 'asserts' keyword has been added
to do assertions. The 'widefp' type number type has been
dropped and, while the 'strictfp' type was suppose to be
added it has not been confirmed that it is usuable.



Object Oriented Keywords

Following is a description of each of these keywords.
Additional short
definitions for each keyword are included
in later tables for reference.

package

We can start with the package keyword. The package
provides a supercontainer
for a set of class definitions.
The package is a directory level structure that is used
to
organize a group of classes that have been created
to serve a related purpose. We
saw descriptions of the
Java classes when we looked at the documentation.

You can also put your own Java classes in a package
by including the package keyword followed by an
identifier
at the head of a source file.


Example
           

package MyPackage;

// go on to create a java class that will be put in this package
 

import    // similar to including header files in C

These packages can be made available to a program by
'importing' them using the
import keyword. For instance,
if we were going to go about building a GUI using
the
old AWT classes, we could make them available by
importing the awt package.


Example     

import java.awt.*;

// the wild card indicates you want all the classes in the package available  
 
JDK 5 introduces a new idea of importing static members
of classes by themselves.

Importing static Class Members   // new in JDK1.5.0

import static java.lang.Math.PI;

class Keywords{
public static void main(String[] args){
System.out.println
("Accessing PI without class qualification : " + PI);

}
}
            


class

The class is the basic working unit of an object oriented
language. Classes are typically stored inside packages
that are 'themed' for example, the 'java.sql' package.
Classes hold variables, constructors and methods and
sometimes inner classes. Normally, the supplied Java
library of classes are used in conjunction with our own
user defined  classes. Classes may be public or protected.
Inner classes can be static, private and protected.


new

The classes we define in Java serve as templates for
executable and customizable working copies
of classes
called 'objects' or 'instances'. For example, a Student
class that represents an information form may be used
over and over to
collect data about a class of students.

Each instance of the Student class would be a unique
version of the student class. The 'new' keyword is
instrumental in creating
these new instances of the class.
We will see new used over and over
in statements
as the following example shows. 

Example       

Student mike = new Student( "Mike Stand" );

extends  
// extends replaces the single colon extension mechanism of C++ 

A major principle used in object oriented languages is
the idea of inheritance. In
simple terms, inheritance
allows one class definition to build on or extend on a
previously created
class. The 'extends' keyword is
used to
allow classes to be created as extensions of
other class. The extended class is
often referred to
as the child that inherits from a parent class. Notice
where the
extends keyword fits in a class definition.
Assume we have a generic class called
IceCreamDish.
This class is extended by 'BananaSplit' below.

Example   

class BananaSplit extends IceCreamDish{
  // add variations       
  }


interface
// a data type that augments a class definition

There are just two other complex data structure types
in Java beside the class.
They are the array, which we
have used to pass arguments from the
command line,
and the interface. The interface is an abstract data type
used to
specify behavior without providing any concrete
implementation for it. The
interface is used to augment
a classes definition in a specific manner. It defers the
implementation to a class that implements it. Practically
this
means an interface defines abstract methods and
constants.

Abstract methods are like function prototypes in C. They
do not have implementations specified inside curly braces
.
A class that implements an interface will provide definitions
for
the interface's methods. The interface is Java's way of
providing some extra
functionality to a class without tying it
into the class inheritance hierarchy.


Example

 interface Runnable{
       void run( );
       }

Interface methods and contstants are public and abstract
by default.


implements

A class can implement the interface using the implements
keyword. While
classes can be extended, interfaces get
implemented. C
onsider a set of cars such as a mini-van,
a sedan and a sports utility vehicle. Now
a new feature is
wanted that is to be used by all three of these extensions
perhaps
bullet proof models in each category.

The bullet proof features could be planned in an interface
and then each class could implement the features in their
own way.
 

Example   

SUV extends GenericChassis implements BulletProof {/**/}


If more than one interface is implemented the interfaces
are separated by commas.

Example

class Guard implements VisualListener, AudioListener{/**/}


this  
// same this that is used in C++   

The 'this' keyword, offers a mechanism to refer to 'this',
the class that contains the 'this' reference. Often when
inside the body of a method inside a class 'this' is used
to
refer to a variable or method that is defined in class
scope, within the scope of the curly
braces associated
with the class definition.

The 'this' keyword can be used to make such an explicit
reference.
The following example shows this in action.
Note in passing that the new keyword has
been used in
the main method to create an object of ThisT. You will
see, 'this' used in other contexts as well.

Example 

class ThisT{
   int x =10;
         ThisT( ){
           int x=4;
           System.out.println(x);        // prints local x value
           System.out.println(this.x);    // prints x defined in class scope
           }
       public static void main(String[] args){
           new ThisT( );
           }
       }
---------------------------------
C :\>  4              //    output
          10
 

super

The 'super' keyword is similar to this. Instead of pointing
to this, the containing class, it points to the parent class.
It allows access to inherited features. Notice the example
below uses the extends keyword to extend the ThisT
class we defined above. This class builds the parent
which outputs the first two lines of the output below.
The second two lines of output reflect the this.x and
super.x calls of the extension class.

Example  // extends the class above

class Too extends ThisT{
   int x =2;
     Too( ){
     System.out.println(this.x);
     System.out.println(super.x);
     }

public static void main(String args[]){
    new Too( );
    }
  }
----------------------
C:\>  4               //    output
         10
         2
         10


instanceof

The keyword 'instanceof' is a Java operator that tests
whether two java objects
are related by inheritance. In
the above examples, if we tested Too class, we
would
find it is an object of type ThisT class, that is a child
of 'ThisT' class.  We can borrow the label object
we
defined earlier and test if it is an instance of Object class.
This will return true
and is very predictable since every
object is a descendant of the Object class type.

The 'instanceof' keyword does not follow the typical Java
naming pattern where the first word in an identifier for a
variable or method is lowercase and the following word
is uppercase. This is consistent another convention that
supercedes the one used for identifiers where all Java
keywords use all lowercase letters.

 Example

JLabel label = new JLabel( " GUI Label " );

if (label instanceof Object) {
System.out.println
("Prints as every object descends from Object class.");

   }


Keywords Used in Flow Control

Java is pretty conventional in the use of keywords to
control the logical path a program follows as it is
executed. We look at these in the next class so we
example them briefly and move on.

if

We have seen already how if is used to test whether
something is true or false. Some code may be executed
if the test returns true. Other it won't be executed.

The general form if statements take is as follows.

Example

if (boolean trueORfalse)
// the next statement or block is executed if the boolean test is true

else

The else keyword can provide an alternate route for the
execution of an if statement. Else provides a way of
executing a section of code if something is false.

Example

if (false)

{ System.out.println ("Evaluates to true"); }
else
{
System.out.println ("Evaluates to false");

// will output false as else block is executed


for

The for keyword provides a way to do some action
repetitively for as long as some condition is true. The
for statement includes a initialization zone, a test area
and a increment area allowing the for statement to
iterate for specific numbers of times.


Example

String[] name = { "Vincent", "Van", "Gough"};
for (int i=0; i<name.length; i++){
     System.out.println( (i+1) +": " + name[i]);
     }

while

The while keyword also lets something happen for as
long as test condition is true. This might be forever.

do

The do keyword can be combined with while to make
sure a section of code is executed at least once.

Example       class doT{
                           public static void main(String[] args){
                             boolean flag=false;
                             do{int x=0;
                              x=x+1;
                             System.out.println(x);
                             }while (flag);    
                            //   x will always at least be set to 1

                          }
                      }

switch

The switch keyword names a logical structure that allows
several cases to be possible execution routes given certain
conditions. A lot of keywords are dedicated to supporting
the switch structure.

case

The keyword case is used in to represent each possible
branch of execution in a case statement.

default

If there is no match for a case in a switch statement,
and the programmer wishes to
provide a response for
this event, the default keyword is used.

break

The break keyword also appears in a switch, and can
be used with for loops as well, and is used to exit a
branch of execution after a particular case has been
selected.


Example

// for (int i =0; i <6; i++){

  switch(i){
      case 0: System.out.println("Summer");
      break;
      case 1: System.out.println("Spring");
      break;
      case 2: System.out.println("Winter");
      break;
      default:  System.out.println("Default is Fall");
      }

//       }  
// results in default case being printed 3 times

continue

The continue keyword is used to for loops to skip out
of the one cycle of a loops execution. 


return

The 'return' keyword is a flow control term designed for
returning a value or returning from a block of code. The
return keyword is usually used in a method, to return
some value. The return keyword can also be used to exit
a situation early based on some condition. The following
two code examples show these two uses of return. First
return used to exit the main method based on a condition.
The second example shows how return is used to return
values from methods.

Example 1 

class Do{
     // a review of taking parameters from the command line.
     public static void main(String[]args){
       if(args.length<1){
         System.out.println
        ("Add \'JACKPOT\' or some other word to the command line after \'java Do\'");
         return;          // return in action
         }
       if(args[0].equals("JACKPOT")) {
         System.out.println("You win the Jackpot!");               
         }
        else
        System.out.println(args[0] + " is your word");
        }
    }

 Example 2 

 /* a method that appends a name to a phrase */
 
 public String Greetings(String name){

          String together="Hello there " + name;
          return together;
          }

void

A Java method by definition must have a return value. In
the case where the method does not return anything it is
declared as returning void as is shown in the following
example.

Example      void out(String s){
                            System.out.println(s);
                           }


Keywords Used with Exceptions


In programs things can go wrong, and in fact it is expected!
A network connection may
fail or a person may accidentally
enter a number where a letter should be in a form. These

kind of errors we expect to happen.

Exception handling is an extension of flow control. It is a
specialized flow control that deals with managing the course
a program should
follow should something go wrong. Java
uses a very uniform and formal model to handle
exceptions.


throws

Any method defined in the Java library or by a programmer
that is capable
of generating some kind of trouble that could
crash a program must be labeled using the
'throws' keyword.
The method signature is extended to state what exception
the method might throw. This is done using the throws
keyword.
Methods in the java.io package provide many
examples. Most of the methods
in the classes of this package
throw IOException. Following is a method defined in the

BufferedInputStream class. Notice it throws IOException.


Example  
 

public int read( ) throws IOException
 

throw

A Java programmer can use the inheritance features of
Java to create extensions of the
Exception classes. The
programmer then use the 'throw' keyword to raise these
exceptions under specific
error conditions.


Example  
 

throw new CustomException(  );
 

try

Java supplies a 'try catch finally' block combination to
handle exceptions inside a Java program. They allow
a
Java program to continue in a normal fashion, (The program
doesn't crash!). The try
block is where methods that might
create exceptions are called.


catch

If an exception should occur in the try block, a catch
block is provided to 'catch' the
exception. The catch
block may provide some feedback and then decides
what next
should happen in the program, whether to
gracefully exit or to continue.

finally

Should there be tasks that should be handledd whether an
exception is thrown or
not, or, if some unknown exception,
has been thrown a finally block can be supplied
to ensure
certain actions are always taken.

Following are a couple of examples that show exception
handling keywords in action.


Example

  try {
      Thread.sleep(3000);
      } //sleep for 3 seconds

  catch(InterruptedException ie)
      { 
  
    System.out.println(ie);
      }

    finally
     { 
      // close out database connections
      // write to a log
     
};


 Example
  
  try {
      Double d = new Double(args[0]);
      }
  catch(NumberFormatException ie)
      {
      System.out.println("Number Format Exception");
      }
     finally
     {
     System.out.println("**************"); 
     }   

      .


Access  Modifiers


The access modifiers offer the programmer the means of
limiting access of individual members of classes and also
of classes themselves. Following are the keywords used
to control access in Java.

private

The private keyword can be applied to variables, methods
and constructors. When a member is marked private it is
accessible only to the class. This includes children classes
that extend a parent class. While the child class inherits the
utility of the parents private members, they cannot directly
access a parent's private members.  A constructor marked
private, makes the constructor unavailable to all except the
class inself. Classes cannot be marked private with the
exception of Inner Classes.

'no modifier'

'no modifier' a.k.a. 'package' or 'default' access is the
privilege level provided when no explicit access modifier
is used with a class member. It is put in italics to signal
that 'no modifier' is not a keyword and in fact it is the
absence of any keyword that describes the access level.
When no access modifier is provided the access is
restricted to the package. This means one class in a
package can access all but private members of another
class in the package.

protected 

The protected keyword describes package access plus
special access provided to children classes, whether
the children classes reside inside the parents package
or outside.  The 'protected' keyword provides a technique
for providing access to members to extension classes,
even in the special case where that child is defined inside
another package.

public


The 'public' keyword describes the most open state of
accessibility. This is the status that is usually used by
members of Java library classes whose fields and methods
and designed to be used by the public at large. The public
keyword describes system wide access.


Example

public class BankAccessPINs{
  private int vault=123456;
             // class access
 
           int locker_room=987654;  /* <--no modifier */
             // package access

   protected int co_insurance_policy=102938;
             // package and sub-classes outside package

    public int ATM_Machines=0;
             // public
    }
 


Special Modifiers  // abstract, final, static, synchronized & native


Where Applied

Following the access modifiers are the keywords 'abstract',
'final' and 'static'. The first
two, 'abstract' and 'final' can be
applied to whole classes. The 'static' keyword can only
be
applied to a whole class only as long as it is defined as an
inner class, inside the confines
of another class. All three
of these
modifiers can be applied to elements smaller than
the class as well.

Java Constants

Often you see static and final used together as in the main
method which is marked
static and final. The closest thing
to a global constant there is in java is marking a variable

public static and final. Making the constant all upper-case
signals this to the user of your
class.

Example   

public static final int GAME_KEY= 920394857127;  

// a constant

// note the Swing Constants are a set of constants but
// are 'package' access, restricted to Swing


abstract

The 'abstract' keyword relates to one of object-oriented
programming's pillars known as 'abstraction'. Essentially,
this is a notion of design where one attempts to isolate
the key characteristics of a system without getting
bogged down in implementation details. One attempts
to describe something in the 'abstract'.

Practically, the 'abstract' keyword can be applied to whole
classes or to methods. An abstract class will have zero
or more abstract methods. Abstract methods, those
marked abstract are defined without bodies, (without a
pair of closed curly braces.)


Example

abstract void go( ); // no body


Any class that has an abstract method in it must itself be
marked abstract.

Example

abstract class Scooter{
    abstract void  brake( );
    abstract void accelerate( );
    }

// abstract can be applied to classes and methods

Abstract classes may have features in common with
interfaces in that interfaces by definition define abstract
methods.

An abstract class cannot be instantiated. This forces
the class to be extended in an inheritance relationship.
In practice, an abstract
class will often have a selection
of concrete methods defined, and a few abstract ones
that are left to be implemented
by the programmer who
is extending the abstract class.

Following is another example of an abstract class
containing abstract methods. Notice an abstract method
has a
signature that ends with a semicolon but has no
body defined in curly braces.


Example 

abstract class AbstractBird{
    abstract void getFlightDescription( );
    abstract void getMigrationDescription( );
    abstract void getFeedingPatterns( );
    }


final

When applied to a class, the 'final' keyword has an effect
that is opposite to that of 'abstract'. Defining a class final
makes it unextendable.
Where 'abstract' classes cannot be
instantiated but can be subclassed,
A 'final' class can't be
subclassed but can be instantiated. The Math class in Java
is
final. It can't be extended by inheritance.

When final is applied to a variable it can not be changed once
it is assigned. The final modifier is always involved when

creating constant values in a program.

Methods can be marked final in which case they cannot
be orerridden.

Example

class P{
      final void method( ){
    System.out.println("x");
    }  
  }
   
 class Q extends P{   
   
   public static void main(String[]args){
  
        }
    void method(){
    System.out.println("y");
    }
  }

// doesn't compile

OUTPUT   

> javac Q.java
Q.java:15: method() in Q cannot override method() in P; overridden method is final
        void method(){
             ^
1 error

static

The static keyword makes a class member part of the
class definition exclusively. When
a new object is created
from the class template the 'static' variable or method it
has a
reference to is not a personal copy, rather it is a
direct reference to the one static class
member defined
in the class definition. A good example of something that
would be
good to define as a static variable would be a
counter that incremented everytime a
new object was
created.

The static keyword can also be applied to inner classes
to create static inner classes.


native

The native keyword is applied to methods. Java allows
calls to 'native' methods, that
is to methods written in
the native language used to create the underlying operating
system. (This is typically 'C' ).  The Java Native Interface

is the name of the API that supplies a method that may
be used to integrate code with native code whenever the
need to improve
performance exceeds the need for Java's
portability. It may also make sense when a lot of legacy
code already exists and porting would be impractical.

A program that uses native methods will no longer be
cross platform without making modifications to the code.
It should be noted that using native methods also
represents a potential breach of Java's built-in security
model.

// The Java Native Interface provides a 'recipe' for parallel
// compiling native methods into Java code


synchronized

Java is a multi-threaded environment. Because multiple
threads can operate on shared data there is the potential
that data may suffer corruption. The  'synchronized' keyword
is to mark sections of code that become accessible to a
single thread that has the 'lock' to access this code. Thus
the 'synchronized' keyword is very important in ensuring
data integrity in a multithreaded
environment. 



 Exotic Modifiers    // rarer keywords used in very specific situations

volatile

The volatile modifier is only used in a multithreaded situation.
Java is capable of creating several threads to carry out several
processes simultaneously. The 'volatile' modifier forces a
variable that may be accessed by one of several thread to
store it's value in real memory and not just in cache as the
value may be accessed or changed unpredictably.


transient

The transient modifier is a pretty specialized keyword and
would likely be used only where sensitive data needs to be
protected from being sent over networks. Marking a variable
'transient' prevents it from being serialized and sent over a wire.
You might mark sensitive identifiers for a document transient
in the case where those documents are subject to being sent
over the wire.


strictfp 
// pretty new, taken out of reserver around JDK 1.4 

The strictfp is a modifier that when applied to an interface, class
or method, will
force the contents of that structure to conform to
the strict mathematical standards specified for floating point numbers
by the IEEE, the Institute of Electrical and Electronics Engineers.
This modifier is for special scientific uses where highly predictable
floating point behavior is required.

 

Info from the Sun Site
http://java.sun.com/developer/JDCTechTips/2001/tt0410.html#using


You can use ' strictfp' as a modifier of class, interface,
and method declarations, like this:

  // legal uses of strictfp

strictfp interface A { }

public strictfp class FpDemo1 {
strictfp void f( ) { }
}

 You cannot use strictfp on constructors or methods
 within interfaces:

    // illegal uses of strictfp

interface A {
strictfp void f();
}

public class FpDemo2 {
strictfp FpDemo2() { }
}


The strictfp keyword is used to designate an expression
as "
FP-strict."

 


Reserved Values

Reserved Values

The keywords true, false and null are referred to as
reserved values. They qualify as keywords as they
cannot be used as identifiers. They are called reserved
values as they represent fixed assignable values. 

true & false

The values true and false, are reserved boolean values.
The boolean type takes it's name from George Boole
who invented 'Boolean Logic'. A boolean type can only
have the values true or false. (They cannot be assigned
1 or 0.) These two word are the literal values that may
be assigned to a boolean variable. If a boolean is
declared in class scope and not assigned a value it is
given the default boolean value, false.


Example    

boolean WavingFlag = true;
 

null        // default value for reference types

An object reference declared in class scope that has
been assigned has the default value 'null'.  This is to
say the reference, holds no pointer to an address in
memory. 


Example 
     

JLabel label_B; 

// in class scope the reference holds the value null.


The null keyword can be used in an assignment explicitly.
This might be done when a label is declared locally inside
a method and the compiler requires a default value.

Example  

JLabel label = null;

If a method is called on a reference that holds a null value,
a NullPointerException will be thrown.


Reserved Keywords

const & goto

The reserved words 'const' and 'goto' are not in use. The
'goto' word is reserved to keep it out of use. This may be
a reaction to it's misuse in the early days of programming
where it led to the creation of disorganized 'spaghetti' code.

The 'const' keyword was being considered for use but
remains out of use, perhaps indefinitely.

 // widefp has been dropped so might be thought of as
// having been added to this category


Keyword Short Definitions

Flow Control
 
 if   if is used in the form if ( boolean ) to execute an action if the boolean value is true
 else   else provides an alternate course of action for an if statement when tested  false
 switch   switch is a construct used to allow several different courses of action to be taken 
 for a given condition or case The switch part of the construct tests a variable.
 case   case is used to execute a code block for a given value tested in switch
 break   break is used in a switch construct to prevent other cases from being executed. 
 It is also used to break out of for loops and optionally also control to resume at
 another point in the code.
 default  in a switch, default provides a course of action in the event  that no cases match 
 for   for is used to begin a loop in the form for(int i=0;i<10;i++) { // do something }
 continue   continue provides a way to break out of one of the iterations of loop (and 
 optionally, have control resume at a different block of code)
  do  do is used with while to create a loop that will always execute a least once.
 while  another form of loop that will execute until the test condition is false
 return  return is used inside methods to return a value.  It is also used by 
  itself to exit a method before completion based on some condition. 

Exceptions
 
 try   try precedes a block of code containing a method which may throw an 
 exception. Every try block must have a catch or finally block following it. 
 catch   The catch block handles the exception that may be thrown and  provides 
 an appropriate response. 
 finally  finally tags an optional block which is executed whether or not an 
 exception is thrown.
 throw  throw is used to overtly cause an exception to be thrown
throws   throws is used with a method signature to indicate a method has the potential 
 to throw an exception. ie. public void sleep(int ms ) throws InterruptedException

Modifiers
 
 private  private is an access modifier that restricts to the access to within a class 
 protected  protected is an access modifier that restricts access to within a  package 
 and  to subclasses inside or outside the package
 no modifier  No access modifier restricts access to within the package
 public  The public access modifier provides unrestricted access allowing 
 class members to be accessed from anywhere, in or outside the package 
 static  The static modifier fixes the definition of a variable, a block of code or 
 method with the class rather than the instantiations of that class. 
 abstract   A class may be marked abstract if it has zero or more abstract methods. An 
 abstract class cannot be instantiated. If an abstract class containing abstract 
 methods is subclassed, the subclass must provide an implementation for any 
 of the parents abstract methods or it too must be marked abstract. An abstract 
 method has no body (a scope defined by two curly braces) 
  final  A class marked final cannot be subclassed A variable marked final cannot be 
 changed once it is assigned a value. 
native native is used to describe non-java code that is native to the underlying platform
 transient Data marked transientwill not be serialized  and  is used to protect sensitive 
 data from being transmitted over the network
synchronized  synchronized is used in a multithreaded environment to ensure data that is
 accessible to several concurrent threads, is acted upon one thread at a time.
volatile  The volatile modifier signals the compiler not to do certain optimizations 
 with it in a multithreaded environment as the data could be changed 
 unpredictably by another thread
 strictfp  a keyword that enforces a strict floating point standard specified by the
 IEEE, (Institute of Electrical and Electronics Engineers) 
// for reference: classes can't be private or protected,  though a class can't be static an inner class can.
 

Object Oriented Keywords
 
class A class is a structure whose scope binds data (variables) and actions (methods)
to form a template that can be used to create new unique copies (aka objects,
instances) of the class. Classes can be subclassed, passing on  their collective characteristics and behavior to their offspring. 
 new  The new operator creates a new instance of a class (or an array). It precedes the class 
 constructor in an expression and creates  a unique copy of the class in memory. (The 
 class acts as a template.) example SomeClass sc = new SomeClass( );
 this  this is a special reference used inside methods or constructors to refer to the current object.
 super  super is like this except it provides a means of referencing the immediate superclass 
 of an object. 
 extends  Java's object oriented design incorporates an inheritance mechanism. 
 A class can extend or subclass another class using the extends keyword, 
 thereby inheriting the parent's non-private characteristics and behavior.
 interface   Java doesn't have multiple inheritance. It allows adding behavior  via
 the interface construct. The interface is a reference type  (like the class
 and the array) It's only members are abstract methods and/or constants. 
 implements   implements is the keyword used by a class to declare it implements an 
 interface. i.e. class Responder implements ActionListener {// code }
 package  The package keyword is used to create a new, directory level container 
 or library in the java language. Packages are what you import to provide 
 the libraries of classes you need for your programs.
 import  import is the keyword you use to bring a package into your program so
 you can access it's classes.
 instanceof   instanceof returns a boolean when it tests if a class is an instance of another 
 class or a subclass of another class.

Reserved Keywords
 
 const  const is reserved. In C it is used to make a variable of data type 
 unalterable. In java by the keyword final does this job. 
 goto  goto became a symbol of poor programming. The story goes it 
 was reserved to ensure it would not be reincarnated in Java.

Reserved Values
 
 true   boolean value  // in Java, boolean values have no numerical counterparts
 false   boolean value 
 null this is the value a reference takes when it doesn't reference (or point to) something

 Method Return Value
 
 void   A method must have a return type. void is used by a method to signify it doesn't 
 return any value, or in other words, returns nothing. 



Self Test                     Self Test With Answers

1) Which of the following is not a java keyword

      a) transient
      b) synchronize
      c) volatile
      d) default
 

2) Which of the following has been moved off the reserved list and into
     the list of java keywords?

      a) goto
      b) const
      c) widefp
      d) strictfp
 

3) Which of the following is not used in a switch statement
     a) switch
     b) case
     c) continue
    d) default
 

4) Which of the following is not a keyword defined to be by used when
     handling exceptions
     a )  try
     b )  break
     c) catch
     d) finally
 

5) True or False. Keywords do not allow case variations. _____
 

6) Which of the following pairs of keywords have no functional relation to each other.

a) import & package
b) extends & class
c) implements & interface
d) null & void
 

7) Which of the following is not a keyword used in flow control.

a ) do
b) final
c) while
d) else
 

8) Which of the following keywords would not be used directly as part of the
     structure of a method

a ) throw
b) void
c) return
d) throws
 

9) Which of the following is a keyword directly related to java's
     object oriented nature.

a) this
b) super
c) default
d) instancof
 

10) Which of the following restricts access to the package

a) private
b) no modifier
c)  protected
d)  public              ( b )
 


Keywords Exercise

Q Associate one of the above java keywords with each of the following brief definitions.
    You may want to cut and paste the keyword table that is in the note to provide a more
     organized view of the keywords.
 
  abstract   boolean   break   byte   case   catch   char   class    const    continue   default   do
  double    else   extends   final   finally   float   for   goto   if   implements   import   instanceof
  int   interface    long  native   new   null   package   private   protected   public   return  short
  static  super  switch  synchronized   this   throw   throws  transient   try   void   volatile  while

1)_______- used in source code to assign classes to specific groupings or packages
2)_______- used to bring in classes to make them available for use in source code file
3)_______- a type defining a collection of related data and code that works with this data
4)_______- the keyword used to derive or 'inherit' the contents of another class
5)_______- used to substitute for multiple inheritance, containing abstract methods and/or class constants
6)_______- used by a class to invoke an interface, (the class must implement the interface's method(s)
7)_______- access modifier which allows a class/member to be accessed from outside the package where class resides.
8)_______- modifier restricting access to methods or variables to same class members
9)_______- restricts access to anywhere within a package and also to subclasses outside the package.
10)______-used to mark occurrences of a method which has been declared but not implemented (no body)
11)______- belonging to the class, describes code which exists 'as one of a kind' of which new copies cannot be created
12) ______- used to queue multithreaded accesses to a shared section of code
13) volatile- prevents compiler optimization for variable that might change asynchronously in a threaded environment (rare)
14) ______- makes a variable or method unchangeable by subclasses
15)______- applies only to methods written in non-java, platform dependent code, i.e. C
16)______- a keyword which enables the referencing of the current or 'containing' instance
17)______- enables referencing the parent or superclass.
18)______- the reference value for a nonexistent instance
19)______- used in methods to indicate a method does not return a value
20)______- used to create an Exception object in response to a particular event  // throw new Exception( );
21)______- a controlled way of executing a block of code which may create an exception
22)______- marks the block of code used to handle an exception created by a try block
23)______- used with a try/catch block for code executed regardless of the outcome of the try/catch execution
24)______- indicates the type of exception a method may throw
25)______- creates new instances or objects of classes
26)______- tests an instance to see if it is an instance of, or a instance of a subclass of a particular class.

Hint: Keywords representing 1) primitive types, 2) normal flow control, and 3) reserved words are not defined.
 
 
Optional // just an extra exercise

1) Create an abstract class called 'HandHelds'.

2) Supply three abstact methods that will provide general functions that the handheld delivers.

3) Define three subclasses using the 'extends' keyword to extend the HandHeld definition to
     different sorts of Handheld devices. ( ie. cell phone, pager etc.)

4) Use the 'System.out.println( "String") statement to describe responses that would be
    appropriate to the particular class being created.

5) Use javadoc to create a description for the class hierarchy.

6) Practice compiling with packages by adding the classes to a package.