Introduction to Object-Oriented Programming, Sample Programs, Set 3

Published:  December 1, 2001
By Richard G. Baldwin

Java Programming Tutorial # 9002


Preface

This is the third and last in a miniseries of lessons designed specifically to help the students in my "Introduction to Object-Oriented Programming" course study for their exams.  However, others may find the lesson useful as well.

The lesson consists of a set of simple programs, each designed to illustrate one or more important Java OOP concepts.  The concepts involved are identified in the comments at the beginning of each program.

The programs are designed to illustrate the code without providing a detailed discussion of the code.  You are referred to the other lessons in my online Java tutorials for detailed discussions of the OOP concepts illustrated by these programs.

Sample Programs

Program Samp122.java
 
/*File Samp122 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
  The use of the Date class to get and
  to manipulate the current time.

The output consists of the following 
six lines of text.  The program 
displays the current time in the format
shown when the program is run.

Samp122
The current time is:
8:49:57 PM CST
One hour will be:
9:49:57 PM CST
Richard Baldwin

**************************************/

import java.util.*;
import java.text.*;
public class Samp122{
  public static void main(
                        String[] args){
    Samp122Class.doDate();
  }//end main
}//end class Samp122
//===================================//

class Samp122Class{
  public static void doDate(){
    System.out.println("Samp122");
    Date now = new Date();
    long millisNow = now.getTime();
    long oneHourMillis = 
             millisNow + 60*60*1000;
    Date oneHour = new Date(
                    oneHourMillis);
    System.out.println(
      "The current time is:\n"
        + DateFormat.getTimeInstance(
                     DateFormat.FULL).
                          format(now));
    System.out.println(
             "One hour will be:\n"
        + DateFormat.
                  getTimeInstance(
                  DateFormat.FULL).
                  format(oneHour));
                            
    System.out.println(
                    "Richard Baldwin");
  }//end doDate()
}//end class

Program Samp124.java
 
/*File Samp124 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
  The use of the Date class to get and
  to manipulate the current time.

The output consists of the following 
six lines of text.  The program 
displays the current time in the format
shown when the program is run.

Samp124
The current time is:
8:39 PM
One-half hour from now will be:
9:09 PM
Richard Baldwin

**************************************/

import java.util.*;
import java.text.*;
public class Samp124{
  public static void main(
                        String[] args){
    Samp124Class.doDate();
  }//end main
}//end class Samp124
//===================================//

class Samp124Class{
  public static void doDate(){
    System.out.println("Samp124");
    Date now = new Date();
    long millisNow = now.getTime();
    long oneHalfHourMillis = 
             millisNow + 60*30*1000;
    Date oneHalfHour = new Date(
                    oneHalfHourMillis);
    System.out.println(
      "The current time is:\n"
        + DateFormat.
                   getTimeInstance(
                     DateFormat.SHORT).
                          format(now));
    System.out.println(
             "One-half hour will be:\n"
        + DateFormat.
                  getTimeInstance(
                  DateFormat.SHORT).
                  format(oneHalfHour));
                            
    System.out.println(
                    "Richard Baldwin");
  }//end doDate()
}//end class

Program Samp126.java
 
/*File Samp126 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
  The use of the Date class to get and
  to manipulate the current date.

The output consists of the following 
six lines of text.  The program 
displays the current date in the format
shown when the program is run.

Samp126
The current date is:
12/1/01
Tomorrow will be:
12/2/01
Richard Baldwin

**************************************/

import java.util.*;
import java.text.*;
public class Samp126{
  public static void main(
                        String[] args){
    Samp126Class.doDate();
  }//end main
}//end class Samp126
//===================================//

class Samp126Class{
  public static void doDate(){
    System.out.println("Samp126");
    Date now = new Date();
    long millisNow = now.getTime();
    long oneDayMillis = 
             millisNow + 60*60*1000*24;
    Date oneDay = new Date(
                         oneDayMillis);
    System.out.println(
      "The current date is:\n"
        + DateFormat.
                   getDateInstance(
                     DateFormat.SHORT).
                          format(now));
    System.out.println(
       "Tomorrow will be:\n"
        + DateFormat.
                   getDateInstance(
                     DateFormat.SHORT).
                       format(oneDay));
                            
    System.out.println(
                    "Richard Baldwin");
  }//end doDate()
}//end class

Program Samp128.java
 
/*File Samp128 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
  The use of the Date class to get and
  to manipulate the current date.

The output consists of the following 
six lines of text.  The program 
displays the current date in the format
shown when the program is run.

Samp128
The current date is:
Dec 1, 2001
Tomorrow will be:
Dec 2, 2001
Richard Baldwin

**************************************/

import java.util.*;
import java.text.*;
public class Samp128{
  public static void main(
                        String[] args){
    Samp128Class.doDate();
  }//end main
}//end class Samp128
//===================================//

class Samp128Class{
  public static void doDate(){
    System.out.println("Samp128");
    Date now = new Date();
    long millisNow = now.getTime();
    long oneDayMillis = 
             millisNow + 60*60*1000*24;
    Date oneDay = new Date(
                         oneDayMillis);
    System.out.println(
      "The current date is:\n"
        + DateFormat.getDateInstance().
                          format(now));
    System.out.println(
       "Tomorrow will be:\n"
        + DateFormat.getDateInstance().
                       format(oneDay));
                            
    System.out.println(
                    "Richard Baldwin");
  }//end doDate()
}//end class

Program Samp130.java
 
/*File Samp130 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
  The use of the Date class to get and
  to manipulate the current date and 
  time.


The output consists of the following 
six lines of text.  The program 
displays the current date and time 
in the format shown when the program is
run.

Samp130
The current date and time is:
Sat Dec 01 19:59:25 CST 2001
One hour from now will be:
Sat Dec 01 20:59:25 CST 2001
Richard Baldwin

**************************************/

import java.util.*;
public class Samp130{
  public static void main(
                        String[] args){
    Samp130Class.doDate();
  }//end main
}//end class Samp130
//===================================//

class Samp130Class{
  public static void doDate(){
    System.out.println("Samp130");
    Date now = new Date();
    long millisNow = now.getTime();
    long oneHourMillis = 
                millisNow + 60*60*1000;
    Date oneHour = new Date(
                        oneHourMillis);
    System.out.println(
      "The current date and time is:\n"
                                + now);
    System.out.println(
         "One hour from now will be:\n"
                            + oneHour);
    System.out.println(
                    "Richard Baldwin");
  }//end doDate()
}//end class

Program Samp138.java
 
/*File Samp138 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
A method that returns a reference to an
  object.


The output consists of the following 
five lines of text.
  
Samp138
5
Incoming null ref
5
Terminating, Richard Baldwin   

**************************************/

class Samp138 {
  int instanceVar = 5;
  
  public static void main(
                        String[] args){
    Samp138 firstRefToObj = 
                  new Samp138();
    System.out.println("Samp138");
    showInstanceVar(firstRefToObj);

    Samp138 secondRefToObj = 
           Samp138Class.returnRefToObj(
                        firstRefToObj);
                        
    firstRefToObj = null;
    
    showInstanceVar(firstRefToObj);
    showInstanceVar(secondRefToObj);
    
    System.out.println("Terminating," 
                  + new Samp138Name());
  }//end main
  //---------------------------------//
  
  static void showInstanceVar(
                     Samp138 refToObj){
    try{
      System.out.println(
                 refToObj.instanceVar);
    }catch(NullPointerException e){
      System.out.println(
                  "Incoming null ref");
    }//end catch
  }//end showInstanceVar
}//End Samp138
//===================================//

class Samp138Class{

  static Samp138 returnRefToObj(
                     Samp138 refToObj){
    //Return the incoming reference
    return refToObj;
  }//end returnRefToObj()
}//end class Samp138Class
//===================================//

class Samp138Name{
  public String toString(){
    return " Richard Baldwin";
  }//end toString()
}//end Samp138Name

Program Samp140.java
 
/*File Samp140 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
A method that returns a reference to an
  object.  Also illustrates the ability
  to deal with references to objects
  in a fairly complicated manner.  This
  is simply an exercise in handling
  refs to objects.


The program first prompts the user to 
enter a single character at the 
keyboard.

The program then displays a value on 
the screen as shown below.

Finally, the program displays a 
termination message which includes your
name.

The program must produce the correct 
output for any single keyboard 
character.  The following sample 
outputs can be used to determine the 
methodology required to produce the 
correct results.

For an input character of A, 
the output must be:

Samp140
Enter a keyboard char -> A
70
Terminating, Richard Baldwin


For an input character of a, 
the output must be:

Samp140
Enter a keyboard char -> a
102
Terminating, Richard Baldwin  

  
For an input character of 0, 
the output must be:

Samp140  
Enter a keyboard char -> 0
53
Terminating, Richard Baldwin    

**************************************/
  

class Samp140 {
  int instanceVar;
  
  public static void main(
          String[] args) 
            throws java.io.IOException{
    Samp140 refToObj = 
                  new Samp140HelperA().
                      returnRefToObj();
    System.out.println("Samp140");
    System.out.print(
          "Enter a keyboard char -> ");
    int charIn = System.in.read();
    refToObj.instanceVar = charIn;
    refToObj = new Samp140Helper(
            refToObj).returnRefToObj();
    show(refToObj);
    System.out.println("Terminating," 
                  + new Samp140Name());
  }//end main
  
  static void show(Samp140 refToObj){
    System.out.println(
                 refToObj.instanceVar);
  }//end show
}//End Samp140 class
//===================================//

class Samp140Helper{
  int instanceVar;
    
  Samp140Helper(Samp140 obj){
    instanceVar = obj.instanceVar;
  }//end constructor
  
  Samp140 returnRefToObj(){
    Samp140 newObj = new Samp140();
    newObj.instanceVar = 
                  this.instanceVar + 5;
    return newObj;
  }//end returnRefToObj()
    
}//end Samp140Helper

class Samp140HelperA{
  Samp140 returnRefToObj(){
    return new Samp140();
  }//end returnRefToObj()
}//end Samp140HelperA

class Samp140Name{
  public String toString(){
    return " Richard Baldwin";
  }//end toString()
}//end Samp140Name

Program Samp150.java
 
/*File Samp150 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the getClass method of the 
Object class, and a couple of methods
of the Class class.


Note that the method named getClassObj
in the class named Samp150Class must 
not be overloaded.

Depending on whether the value of rNum
is odd or even, the output consists of
one of the following groups of four 
lines of text.  Because the program
generates the data on the basis of a 
random value, the output will differ 
from one run to the next.  However, in
all cases, the output will match one 
of the groups of four lines of text 
shown below.

Samp150 String
Richard Baldwin
java.lang.String
class java.lang.Object

Samp150 Button
Richard Baldwin
java.awt.Button
class java.awt.Component

**************************************/
  
import java.awt.*;
import java.util.*;

class Samp150{

  public static void main(
                        String[] args){
    Random rGen = new Random(
                 new Date().getTime());
    int rNum = rGen.nextInt()%2;

    Class refToClassObj;
    if( rNum == 0){
      System.out.println(
                     "Samp150 String");
      refToClassObj = Samp150Class.
           getClassObj(new String(""));
    }else{ 
      System.out.println(
                     "Samp150 Button");
      refToClassObj = Samp150Class.
             getClassObj(new Button());
    }//end else
    
    System.out.println(refToClassObj.
                            getName());
    System.out.println(refToClassObj.
                      getSuperclass());
  }//end main
}//end class Samp150
//===================================//

class Samp150Class{
  public static Class getClassObj(
                      Object objectIn){
    System.out.println(
                    "Richard Baldwin");
    Class refToClassObj = null;
    try{       
      refToClassObj = objectIn.
                            getClass();
    }catch(Exception e){
                System.out.println(e);}
    return refToClassObj;
  }//end getClassObj();
}//end class Samp150Class

Program Samp160.java
 
/*File Samp160 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
  Use of the forName() method of the 
  class named Class.


Depending on whether the value of rNum
is odd or even, the output consists of
one of the following groups of four 
lines of text.  Because the program
generates the data on the basis of a 
random value, the output will differ 
from one run to the next.  However, in
all cases, the output will match one of
the groups of four lines of text shown
below.

Samp160 Button
Richard Baldwin
java.awt.Button
class java.awt.Component

Samp160 String
Richard Baldwin
java.lang.String
class java.lang.Object

**************************************/

import java.awt.*;
import java.util.*;

class Samp160{

  public static void main(
                        String[] args){
    Random rGen = new Random(
                 new Date().getTime());
    int rNum = rGen.nextInt()%2;
    
    Class refToClassObj;
    if(rNum == 0){
      System.out.println(
                     "Samp160 String");
      refToClassObj = Samp160Class.
                  returnClassObj(
                   "java.lang.String");
    }else{
      System.out.println(
                     "Samp160 Button");
      refToClassObj = Samp160Class.
                   returnClassObj(
                    "java.awt.Button");
    }//end else
    
    System.out.println(refToClassObj.
                            getName());
    System.out.println(refToClassObj.
                      getSuperclass());
  }//end main
}//end class Samp160
//===================================//

class Samp160Class{  
  public static Class returnClassObj(
                      String stringIn){
    System.out.println(
                    "Richard Baldwin");
    Class refToClassObj = null;
    try{       
      refToClassObj = Class.forName(
                             stringIn);
    }catch(Exception e){
                System.out.println(e);}
    return refToClassObj;       
  }//end returnClassObj();
}//end class Samp160Class

Program Samp170.java
 
/*File Samp170 
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the asList method of the Arrays
class to get a List view of an array.
Note that changes to the List view
write through to the underlying array.


The output consists of the following 
four lines of text.

Samp170
Richard Baldwin
A B C 
Ax Bx Cx

**************************************/
  
import java.util.*;
class Samp170{
  public static void main(
                        String[] args){
    System.out.println(
          Samp170Class.showYourName());
    
    Object[] refToArray = 
                         {"A","B","C"};
    //Display array contents
    for(int cnt=0;
          cnt<refToArray.length;cnt++){
      System.out.print(
                refToArray[cnt] + " ");
    }//end for loop
    System.out.println();
    
    List refToList = Samp170Class.
            returnListView(refToArray);
    ListIterator iterator = 
              refToList.listIterator();
    //Modify List contents
    while(iterator.hasNext()){
      Object var3 = iterator.next();
      iterator.set(var3 + "x");
    }//end while
    
    //Display modified array contents
    for(int cnt=0;
          cnt<refToArray.length;cnt++){
      System.out.print(
                refToArray[cnt] + " ");
    }//end for loop
    System.out.println();
  }//end main
}//end class Samp170  
//===================================//

class Samp170Class{
  static String showYourName(){
    System.out.println("Samp170");
    return "Richard Baldwin";
  }//end showYourName()
  
  static List returnListView(
                  Object[] refToArray){
    return Arrays.asList(refToArray);
  }//end returnListView

}//end class Samp170Class

-end-


Copyright 2001, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-