JMU
Java
An Introduction for Programmers


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Identifiers
Comments
Some Atomic/Primitive/Fundamental Types in Java

Type Memory Range
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to 2,147,483,647
float 4 bytes
double 8 bytes
char 2-4 bytes Unicode
boolean true or false

Variable Declarations in Java
Assignment Operator
The final Modifier in Java
The if Statement
while Loops
do-while Loops
for Loops
Arrays
Arrays Utility Class

The Arrays class (in the java.util package) contains several static methods that are very convenient when working with arrays.

    import java.util.Arrays;

    int     target;
    int[]   a;

    a = new int[100];

    Arrays.fill(a, 0);        // Fill a with zeroes
    Arrays.fill(a, 1, 10, 99) // Fill a[10] thru a[99] with ones

    ...

    Arrays.sort(a);           // Sort a in ascending order


    //  Searches for 5 in a and returns 5 if found
    //  The array must be sorted
    //
    target = Arrays.binarySearch(a,5);
    
Classes
Classes: Accessibility of Members
Classes: Declaring Methods
Classes: Class-Members
Classes: An Example
javaexamples/oopbasics/pictureframe/overloadedmethods/PictureFrame.java
        /**
 * An encapsulation of a picture frame.
 *
 * This version has overloaded methods.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 6.0
 */
public class PictureFrame
{
    private static final double DOLLARS_PER_IN_OF_FRAME    = 0.15;
    private static final double DOLLARS_PER_SQ_IN_OF_GLASS = 0.05;    

    private boolean    stand;    
    private double     height, matte, width;

    /**
     * Construct a PictureFrame object.
     *
     * Note: Negative values are converted to positive values 
     * and the width and height are put in canonical form 
     * (i.e., a portrait orientation).
     *
     * @param width   The width (in inches)
     * @param height  The height (in inches)
     * @param matte   The size of the matte (in inches) on all 4 sides
     * @param stand   true if there is a built-in stand
     */
    public PictureFrame(double width, double height, double matte, 
                        boolean stand)
    {
        double     h, w;
        
        h = Math.abs(height);
        w = Math.abs(width);

        this.width  = Math.min(w, h);
        this.height = Math.max(w, h);
        this.matte  = Math.abs(matte);
        this.stand  = stand;
    }
    
    /**
     * Construct a PictureFrame object with no matte and no stand.
     *
     * @param width   The width (in inches)
     * @param height  The height (in inches)
     */
    public PictureFrame(double width, double height)
    {
        this(width, height, 0.0, false);
    }

    /**
     * Calculate the area of this PictureFrame.
     *
     * @return  The area (in square inches)
     */
    private double area()
    {
        return width * height;
    }

    /**
     * Calculate the area of the matte.
     *
     * @return  The area (in square inches)
     */
    private double matteArea()
    {
               // Top and Bottom   + Sides (not including the top and bottom)
        return 2.0*(matte * width) + 2.0*(matte * (height - 2.0*matte));
    }

    /**
     * Calculate the perimeter of this PictureFrame.
     *
     * @return  The area (in inches)
     */
    private double perimeter()
    {
        return 2.0*width + 2.0*height;
    }

    /**
     * Return true if the owning PictureFrame and the given PictureFrame
     * have the same attributes.
     *
     * @return  true if the attributes are the same; false otherwise
     */
    public boolean equals(PictureFrame other)
    {
        return (this.width == other.width) && (this.height == other.height)
            && (this.matte == other.matte) && (this.stand == other.stand);
    }

    /**
     * Return the cost of this PictureFrame (which is a function
     * of the perimeter and the area) in dollars.
     *
     * @return   The cost
     */
    public double getCost()
    {
        double     frame, glass;
        
        frame = perimeter() * DOLLARS_PER_IN_OF_FRAME;
        glass = area() * DOLLARS_PER_SQ_IN_OF_GLASS;

        return frame+glass;
    }

    /**
     * Get the height of this PictureFrame.
     *
     * @return   The height
     */
    public double getHeight()
    {
        return height;
    }

    /**
     * Get the size of the matte.
     *
     * @return   The size of the matte
     */
    public double getMatte()
    {
        return matte;
    }

    /**
     * Get the width of this PictureFrame.
     *
     * @return   The width
     */
    public double getWidth()
    {
        return width;
    }
    /**
     * Return the visible area (in square inches) of the content
     * contained in this PictureFrame.
     *
     * @param    max   true for the maximum possible (i.e., unmatted) area 
     * @return   The visible area
     */
    public double getVisibleArea(boolean max)
    {
        double   result;
        
        result = area();
        if (!max) result -= matteArea();

        return result;
    }

    /**
     * Return the visible area (in square inches) of the content
     * contained in this PictureFrame.
     *
     * @return   The visible area
     */
    public double getVisibleArea()
    {
        return getVisibleArea(false);
    }

    /**
     * Return a human-readable String representation of this PictureFrame.
     *
     * @param   terse  true for a terse representation
     * @return         The String representation
     */
    public String toString(boolean terse)
    {
        String      result;

        if (terse)
        {
            result = ""+width+"x"+height;
        }
        else
        {
            result = ""+width+"in. x "+height+"in.";
            if (matte > 0.0) result += " with a "+matte+"in. matte";
            if (stand)       result += " (w/ stand)";
        }
        
        return result;
    }

    /**
     * Return a human-readable String representation of this PictureFrame.
     *
     * @return         The String representation
     */
    public String toString()
    {
        return toString(false);
    }
}
        
Enumerated Types
Enumerated Types: An Example
javaexamples/oopbasics/months/v2/Month.java
        /**
 * An enumerated type for the months of the year
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 2.0
 */
public enum Month
{
   JANUARY   ("January",  31),
   FEBRUARY  ("February", 28),
   MARCH     ("March",    31), 
   APRIL     ("April",    30),
   MAY       ("May",      31),
   JUNE      ("June",     30), 
   JULY      ("July",     31),
   AUGUST    ("August",   31),
   SEPTEMBER ("September",30),
   OCTOBER   ("October",  31),
   NOVEMBER  ("November", 30),
   DECEMBER  ("December", 31);

   private final int    days;
   private final String name;

   /**
    * Explicit Value Constructor.
    *
    * @param name   The name of the Month
    * @param days   The number of days in the Month
    */
   private Month(String name, int days)
   {
      this.name = name;
      this.days = days;
   }

   /**
    * Get the 3-letter abbreviation for this Month.
    *
    * @return  The 3-letter abbreviation
    */
   public String getAbbreviation()
   {
      String       result;
      
      if (name.length() > 3) result = name.substring(0,3)+".";
      else                   result = name;

      return result;      
   }

   /**
    * Get the numeric value of this Month (in the interval [1,12]).
    *
    * @return  The numeric value of this Month
    */
   public int getNumber()
   {
      return ordinal()+1; // ordinal() returns the position in the declaration
   }

   /**
    * Get the (normal) number of days in this Month.
    *
    * @return  The normal number of days in this Month.
    */
   public int getLength()
   {
      return days;      
   }
   
   /**
    * Return the Month that corresponds to a given String.
    *
    * @param s   The String representation
    * @return    The corresponding Month (or null)
    */
   public static Month parseMonth(String s)
   {
       Month[] all;
       all = Month.values();
       for (int i=0; i<all.length; i++)
       {
          if (s.equalsIgnoreCase(all[i].name) 
              || s.equalsIgnoreCase(all[i].getAbbreviation()))
          {
              return all[i];
          }
       }
       return null;
   }
   
   /**
    * Get a String representation of this Month
    *
    * @return   The String representation (i.e., the name)
    */
   public String toString()
   {
      return name;      
   }
}
        
Specialization
Preventing Specialization
A Peculiarity of Specialization in Java
Abstract Classes/Methods
Interfaces
Parameterized Classes
Parameterized Classes: An Example
javaexamples/parameterized/Identified.java
        /**
 * A parameterized (i.e., type-safe) encapsulation of an Identified entity.
 *
 * @author  Prof. David Bernstein, James Madison University
 */
public class Identified<T>
{
    private int       id;
    private T         entity;
    
    /**
     * Explicit Value Constructor.
     *
     * @param id      The unique identifier for the entity
     * @param entity  The entity
     */
    public Identified(int id, T entity)
    {
        this.id     = id;
        this.entity = entity;
    }
    
    /**
     * Get the ID of this Identified entity.
     *
     * @return   The ID
     */
    public int getID()
    {
        return id;
    }

    /**
     * Get the entity.
     *
     * @return   The entity
     */
    public T getEntity()
    {
        return entity;
    }
}
        
Parameterized Classes: Using
javaexamples/parameterized/Driver.java (Fragment: 0)
                Identified<Person>   person;
        Identified<Product>  product;
        
        
        person  = new Identified<Person>(   10, new Person());
        product = new Identified<Product>(3415, new Product());


        Person fred;
        fred   = person.getEntity();  // This will compile

        Person barney;
        barney = product.getEntity(); // This will not compile
        
Bounded Type Parameters
Bounded Type Parametetrs: An Example
javaexamples/parameterized/bounded/Identified.java
        /**
 * A bounded parameterized encapsulation of an Identified entity.
 *
 * @author  Prof. David Bernstein, James Madison University
 */
public class Identified<T extends Person>
{
    private int       id;
    private T         entity;
    
    /**
     * Explicit Value Constructor.
     *
     * @param id      The unique identifier for the entity
     * @param entity  The entity
     */
    public Identified(int id, T entity)
    {
        this.id     = id;
        this.entity = entity;
    }
    
    /**
     * Get the ID of this Identified entity.
     *
     * @return   The ID
     */
    public int getID()
    {
        return id;
    }

    /**
     * Get the entity.
     *
     * @return   The entity
     */
    public T getEntity()
    {
        return entity;
    }
}