Java Programming Tutorial # 9001
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.
/*File Samp076
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
Interface definitions,
Implementing one or more interfaces
in class definition,
Defining interface methods in class
definition,
Casting from one interface type
to another.
The output consists of the following
five lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. However, in
all cases:
1. The values in the first row of
numbers will be a sequence of
consecutive integers in increasing
algebraic order from left to right.
2. All three values in the second row
of numbers will match the value of the
center number in the first row of
numbers.
Samp076
Richard
Baldwin
-64 -63 -62
-63 -63 -63
**************************************/
import java.util.*;
class Samp076{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();
//Store refs to objs in ref vars of
// interface types
Samp076IntfcA var1 =
new Samp076ClassA(rNum);
Samp076IntfcB var2 =
new Samp076ClassB(rNum);
//Invoke interface method on refs
// to objects. Note that
// implementations of interface
// method differ. Note rqmt for
// cast.
System.out.print(
var1.getModifiedData() + " ");
System.out.print(rNum + " ");
System.out.println(
((Samp076IntfcA)var2).
getModifiedData());
//Invoke interface method on refs
// to objects. Note that
// implementations of interface
// method are the same. Note rqmt
// for cast.
System.out.print(
((Samp076IntfcB)var1).
getData() + " ");
System.out.print(rNum + " ");
System.out.println(
var2.getData());
}//end main
}//end class Samp076
//===================================//
interface Samp076IntfcA{
public int getModifiedData();
}//end interface
//===================================//
interface Samp076IntfcB{
public int getData();
}//end interface
//===================================//
class Samp076ClassA
implements Samp076IntfcA,
Samp076IntfcB{
private int data;
Samp076ClassA(int data){
System.out.println("Samp076");
System.out.println("Richard");
this.data = data;
}//end constructor
//Define interface method
public int getModifiedData(){
return data - 1;
}//end getModifiedData()
//Define interface method
public int getData(){
return data;
}//end getData()
}//end class Samp076ClassA
//===================================//
class Samp076ClassB
implements Samp076IntfcA,
Samp076IntfcB{
private int data;
Samp076ClassB(int data){
System.out.println("Baldwin");
this.data = data;
}//end constructor
//Define interface method
public int getModifiedData(){
return data + 1;
}//end getModifiedData()
//Define interface method
public int getData(){
return data;
}//end getData()
}//end class Samp076ClassB
|
Program Samp078.java
/*File Samp078
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,
Use of the forName method of the
Class class,
Use of the getInterfaces method of
the Class class,
Use of the getSuperclass method of
the Class class,
The output consists of the following
lines of text. Because the program
generates random data for testing, the
numeric values will differ from one run
to the next. However, the two values
will be the same.
Note that a space was manually inserted
near the end to force the material to
fit in this narrow format.
Samp078
Richard Baldwin
74 74
Samp078ClassA
class java.lang.Object
interface Samp078IntfcA
interface Samp078IntfcB
java.awt.Button
class java.awt.Component
interface javax.accessibility.
Accessible
**************************************/
import java.util.*;
import java.awt.*;
class Samp078{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();
//Store ref to obj in ref var of
// interface type
Samp078IntfcB var1 =
new Samp078ClassA(rNum);
//Invoke interface method on ref
// to object.
System.out.print(
var1.getData() + " ");
System.out.println(rNum + " ");
//Get Class obj representing target
// class based on ref to object.
Class var2 = var1.getClass();
//Get and display name of target
// class and name of superclass
// of target class
System.out.println(var2.getName());
System.out.println(
var2.getSuperclass());
//Get and display list of
// interfaces implemented by the
// target class.
Class[] var3 =
var2.getInterfaces();
for(int cnt=0; cnt<var3.length;
cnt++){
System.out.println(var3[cnt]);
}//end for loop
System.out.println();
//Get Class obj representing target
// class based on class name
// as string.
try{
var2 = Class.forName(
"java.awt.Button");
//Get and display name of target
// class and name of superclass
// of target class
System.out.println(
var2.getName());
System.out.println(
var2.getSuperclass());
//Get and display list of
// interfaces implemented by the
// target class.
var3 = var2.getInterfaces();
for(int cnt=0; cnt<var3.length;
cnt++){
System.out.println(var3[cnt]);
}//end for loop
}catch(ClassNotFoundException e){
System.out.println("Error");
}//end catch block
}//end main
}//end class Samp078
//===================================//
interface Samp078IntfcA{
public void intfcMethod();
}//end interface
//===================================//
interface Samp078IntfcB{
public int getData();
}//end interface
//===================================//
class Samp078ClassA
implements Samp078IntfcA,
Samp078IntfcB{
private int data;
Samp078ClassA(int data){
System.out.println("Samp078");
System.out.println(
"Richard Baldwin");
this.data = data;
}//end constructor
//Define interface method as empty
// method
public void intfcMethod(){
//empty method
}//end intfcMethod()
//Define interface method
public int getData(){
return data;
}//end getData()
}//end class Samp078ClassA
//===================================//
|
Program Samp080.java
/*File Samp080
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
Interface definitions,
Implementing one or more interfaces
in class definition,
Defining interface methods in class
definition,
Overridden toString method,
Use of the getClass method of the
Object class,
Use of the getInterfaces method of
the Class class
The output consists of the following
nine lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. However, in
all cases:
1. The values in the first row of
numbers will be a sequence of
consecutive integers in increasing
algebraic order from left to right.
2. All three values in the second row
of numbers will match the value of the
center number in the first row of
numbers.
3. All three values in the third row
of numbers will be algebraically five
greater than the values in the second
row of numbers.
Samp080
Richard
Baldwin
-109 -108 -107
-108 -108 -108
-103 -103 -103
interface Samp080IntfcA
interface Samp080IntfcA
interface Samp080IntfcB
**************************************/
import java.util.*;
class Samp080{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();
//Store ref to obj in ref var of
// interface type
Samp080IntfcA var1 =
new Samp080ClassA(rNum);
Samp080IntfcA var2 =
new Samp080ClassB(rNum);
//Invoke interface method on refs
// to objects. Note that
// implementations of interface
// method differ.
System.out.print(
var1.getModifiedData() + " ");
System.out.print(rNum + " ");
System.out.println(
var2.getModifiedData());
//Invoke interface method on refs
// to objects. Note that
// implementations of interface
// method are the same.
System.out.print(
var1.getData() + " ");
System.out.print(rNum + " ");
System.out.println(var2.getData());
//Invoke overridden toString method
// on refs to objects. Note that
// overridden versions are the
// same.
System.out.print(var1 + " ");
System.out.print(rNum + 5 + " ");
System.out.println(var2);
//Get Class obj representing one
// class.
Class var3 = var1.getClass();
//Get and display list of
// interfaces implemented by the
// target class.
Class[] var4 =
var3.getInterfaces();
for(int cnt=0; cnt<var4.length;
cnt++){
System.out.println(var4[cnt]);
}//end for loop
//Get Class obj and do same for
// the other class.
Class var5 = var2.getClass();
Class[] var6 =
var5.getInterfaces();
for(int cnt=0; cnt<var6.length;
cnt++){
System.out.println(var6[cnt]);
}//end for loop
}//end main
}//end class Samp080
//===================================//
interface Samp080IntfcA{
public int getModifiedData();
public int getData();
}//end interface
//===================================//
interface Samp080IntfcB{
//this is a dummy interface
}//end interface
//===================================//
class Samp080ClassA
implements Samp080IntfcA{
private int data;
Samp080ClassA(int data){
System.out.println("Samp080");
System.out.println("Richard");
this.data = data;
}//end constructor
//Define interface method
public int getModifiedData(){
return data - 1;
}//end getModifiedData()
//Define interface method
public int getData(){
return data;
}//end getData()
//Override toString method
public String toString(){
return "" + (data + 5);
}//end toString()
}//end class Samp080ClassA
//===================================//
class Samp080ClassB
implements Samp080IntfcA,
Samp080IntfcB{
private int data;
Samp080ClassB(int data){
System.out.println("Baldwin");
this.data = data;
}//end constructor
//Define interface method
public int getModifiedData(){
return data + 1;
}//end getModifiedData()
//Define interface method
public int getData(){
return data;
}//end getData()
//Override tostring method
public String toString(){
return "" + (data + 5);
}//end toString()
}//end class Samp080ClassB
|
Program Samp088.java
/*File Samp088
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
Saving object ref as class type,
interface type, or type Object,
Casting ref stored as type Object
to class type or interface type
to access interface method,
Accessing overridden toString
method on references of all three
types without a requirement to
perform a cast.
The output consists of the following
five lines of text.
intfcMethod output
intfcMethod output
Overridden toString output
Overridden toString output
Overridden toString output
**************************************/
import java.util.*;
class Samp088{
public static void main(
String[] args){
String strData = "";//for use later
Samp088Class var1 =
new Samp088Class();
Samp088Intfc var2 = var1;
Object var3 = var1;
var1.intfcMethod();
var2.intfcMethod();
//Following will not compile due
// to need for a cast
// strData = var3.intfcMethod();
//Either of the following casts
// will resolve the above problem
strData = ((Samp088Class)var3).
intfcMethod();
System.out.println(strData);
strData = ((Samp088Intfc)var3).
intfcMethod();
System.out.println(strData);
//No cast is required to invoke
// overridden toString method
// for ref stored as class type,
// interface type, or type Object
strData = var1.toString();
System.out.println(strData);
strData = var2.toString();
System.out.println(strData);
strData = var3.toString();
System.out.println(strData);
}//end main
}//end class Samp088
//===================================//
interface Samp088Intfc{
public String intfcMethod();
}//end interface
//===================================//
class Samp088Class
implements Samp088Intfc{
//define interface method
public String intfcMethod(){
return "intfcMethod output";
}//end getData()
//override toString method
public String toString(){
return
"Overridden toString output";
}//end toString()
}//end class Samp088Class
|
Program Samp090.java
/*File Samp090
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
Interface definitions,
Implementing an interface in class
definition,
Defining interface methods in class
definition,
Storing references to new objects in
elements of an array of type
Object,
Cast elements to interface type in
order to invoke methods,
Overridden toString method.
The output consists of the following
six lines of text. Because the program
generates random data for testing, the
actual values will differ from one run
to the next. However, in all cases:
1. The values in the first row of
numbers will be a sequence of
consecutive integers in increasing
algebraic order from left to right.
2. All three values in the second row
of numbers will match the value of the
center number in the first row of
numbers.
3. All three values in the third row
of numbers will be algebraically five
greater than the values in the second
row of numbers.
Samp090
Richard
Baldwin
-68 -67 -66
-67 -67 -67
-62 -62 -62
**************************************/
import java.util.*;
class Samp090{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();
//Create a two-element array
// object of type Object
Object[] var1 = new Object[2];
//Store refs to two new objects
// in the array as type Object
var1[0] = new Samp090ClassA(rNum);
var1[1] = new Samp090ClassB(rNum);
//Cast contents of array elements
// to interface type and invoke
// interface methods on them
System.out.print(
((Samp090Intfc)var1[0]).
getModData() + " ");
System.out.print(rNum + " ");
System.out.println(
((Samp090Intfc)var1[1]).
getModData());
//Do the same and invoke the
// other interface method
System.out.print(
((Samp090Intfc)var1[0]).
getData() + " ");
System.out.print(rNum + " ");
System.out.println(
((Samp090Intfc)var1[1]).
getData());
//Are the following two casts
// required?
System.out.print(
((Samp090Intfc)var1[0]) + " ");
System.out.print(rNum + 5 + " ");
System.out.println(
((Samp090Intfc)var1[1]));
//The two casts above are not
// required. The print method
// invokes the toString method,
// which is not an interface
// method. Rather, it is
// inherited from the class named
// Object and overridden in the
// class named Samp090ClassA.
// However, it is important to
// note that methods inherited
// from the Object class can be
// invoked on references of
// interface types.
}//end main
}//end class Samp090
//===================================//
interface Samp090Intfc{
public int getModData();
public int getData();
}//end interface
//===================================//
class Samp090ClassA
implements Samp090Intfc{
private int data;
Samp090ClassA(int data){
System.out.println("Samp090");
System.out.println("Richard");
this.data = data;
}//end constructor
public int getModData(){
return data - 1;
}//end getModData()
public int getData(){
return data;
}//end getData()
public String toString(){
return "" + (data + 5);
}//end toString()
}//end class Samp090ClassA
//===================================//
class Samp090ClassB
implements Samp090Intfc{
private int data;
Samp090ClassB(int data){
System.out.println("Baldwin");
this.data = data;
}//end constructor
public int getModData(){
return data + 1;
}//end getModData()
public int getData(){
return data;
}//end getData()
public String toString(){
return "" + (data + 5);
}//end toString()
}//end class Samp090ClassB
|
Program Samp098.java
/*File Samp098
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
Use of the Collection Framework, the
List interface, and the ArrayList
class. The ArrayList class implements
the List interface. The add method of
the List interface allows duplicates.
The ArrayList class does not implement
an interface that requires it to
maintain the collections in sorted
order.
Therefore, adding object references
to an object instantiated from a class
that implements List results in a
Collection object that maintains the
collection in the same order that the
items were added, allowing duplicates.
(New items can be added at the end
or inserted anywhere in the list.
However, in order to insert, it is
necessary to treat the reference as
type List or ArrayList and not as type
Collection.)
Note that List is a subinterface of
Collection. Therefore, a class that
implements List also implements
Collection. A reference to an object
of that class can be stored as type
List or type Collection.
This program also illustrates the use
of the Iterator interface for the
purpose of traversing a collection.
The output of this program is as
follows:
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.
Samp098
Richard Baldwin
Harry is first
Harry Joe Bill Sue Tom Bill
Samp098
Richard Baldwin
Mike is first
Mike Bill Tom Mary Mike Alice
**************************************/
import java.util.*;
class Samp098{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = rGen.nextInt()%2;
//Instantiate a new object of a
// class that extends ArrayList and
// store its reference as the
// interface type Collection
Collection var =
new Samp098Class();
//Invoke the add method on the
// object six times in succession
// to add sex new items to the
// collection. Note that they are
// not added in order. Note also
// that there are duplicates.
if(rNum == 0){
System.out.println(
"Harry is first");
var.add("Joe");
var.add("Bill");
var.add("Sue");
var.add("Tom");
var.add("Bill");
//Insert at index 0. Note the
// required cast.
((List)var).add(0,"Harry");
}else{
System.out.println(
"Mike is first");
var.add("Mike");
var.add("Bill");
var.add("Mary");
var.add("Mike");
var.add("Alice");
//Insert at index 2. Note the
// required cast.
((List)var).add(2,"Tom");
}//end else
//Invoke the iterator method on the
// reference to the Collection
// object to get a reference to an
// object of the interface type
// Iterator.
Iterator iter = var.iterator();
//Use the Iterator object to access
// and display all of the items
// in the Collection object.
while(iter.hasNext()){
System.out.print(
iter.next() + " ");
}//end while loop
System.out.println();
}//end main
}//end class Samp098
//===================================//
class Samp098Class extends ArrayList{
//Other than a constructor to display
// the programmer's name and the
// program name, this class doesn't
// require a body. It inherits
// everything needed from ArrayList.
// Therefore, this class is a
// ArrayList class with a special
// constructor.
Samp098Class(){//constructor
System.out.println("Samp098");
System.out.println(
"Richard Baldwin");
}//end constructor
}//end class Samp098Class
|
Program Samp100.java
/*File Samp100
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
Use of the Collection Framework, the
Set interface, and the TreeSet class.
The TreeSet class implements the Set
interface. The add method of the Set
interface doesn't allow duplicates.
The TreeSet class also implements the
SortedSet interface. Classes that
implement the SortedSet interface
maintain their collections in sorted
order.
Therefore, adding object references
to an object instantiated from a class
that implements both Set and SortedSet
results in a Collection object that
maintains the collection in sorted
order without any duplicates.
Note that both Set and SortedSet are
subinterfaces of Collection.
Therefore, a class that implements
either Set or SortedSet also
implements Collection. A reference to
an object of that class can be stored
as Set, SortedSet, or Collection.
This program also illustrates the use
of the Iterator interface for the
purpose of traversing a collection.
The output of this program is as
follows:
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.
Samp100
Richard Baldwin
Bill is first
Bill Joe Sue Tom
Samp100
Richard Baldwin
Alice is first
Alice Bill Mary Mike
**************************************/
import java.util.*;
class Samp100{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = rGen.nextInt()%2;
//Instantiate a new object of a
// class that extends TreeSet and
// store its reference as the
// interface type Collection
Collection var =
new Samp100Class();
//Invoke the add method on the
// object five times in succession
// to add five new items to the
// collection. Note that they are
// not added in order. Note also
// that there are duplicates.
if(rNum == 0){
System.out.println(
"Bill is first");
var.add("Joe");
var.add("Bill");
var.add("Sue");
var.add("Tom");
var.add("Bill");
}else{
System.out.println(
"Alice is first");
var.add("Mike");
var.add("Bill");
var.add("Mary");
var.add("Mike");
var.add("Alice");
}//end else
//Invoke the iterator method on the
// reference to the Collection
// object to get a reference to an
// object of the interface type
// Iterator.
Iterator iter = var.iterator();
//Use the Iterator object to access
// and display all of the items
// in the Collection object. Note
// that they will be accessed in
// sorted order with duplicates
// removed.
while(iter.hasNext()){
System.out.print(
iter.next() + " ");
}//end while loop
System.out.println();
}//end main
}//end class Samp100
//===================================//
class Samp100Class extends TreeSet{
//Other than a constructor to display
// the programmer's name and the
// program name, this class doesn't
// require a body. It inherits
// everything needed from TreeSet.
// Therefore, this class is a TreeSet
// class with a special constructor.
Samp100Class(){//constructor
System.out.println("Samp100");
System.out.println(
"Richard Baldwin");
}//end constructor
}//end class Samp100Class
|
Program Samp106.java
/*File Samp106
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
Use of the binarySearch method of the
Arrays class. This is a simple program
for students who dig deeply enough into
the Sun documentation to learn how to
use the binarySearch method of the
Arrays class. Otherwise, it will be a
fairly difficult problem.
The program searches a sorted array of
Strings to find and return the index
of a key String. If the String is not
in the array, a negative index value
is returned.
The output consists of the following
five lines of text:
Samp106
Richard Baldwin
Dick Harry Tom
Harry is at index 1
Bill is not in array
**************************************/
import java.util.*;
class Samp106{
public static void main(
String[] args){
System.out.println(
Samp106Class.displayName());
//Create an array object of type
// Object. Populate it with refs
// to String objects.
Object[] arrayRef = {
"Tom","Dick","Harry"};
//Sort the array
Arrays.sort(arrayRef);
//Display the contents of the
// sorted array
for(int cnt=0;cnt<arrayRef.length;
cnt++){
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();
//Search the array for a key string
String key = "Harry";
int index = Samp106Class.
searchArray(arrayRef,key);
//Display location of key string
Samp106Class.indexHandler(
index,key);
//Search the array for a key string
// that doesn't exist in the array
key = "Bill";
index = Samp106Class.searchArray(
arrayRef,key);
//Display location of key string
Samp106Class.indexHandler(
index,key);
}//end main
}//end class Samp106
//===================================//
class Samp106Class{
static String displayName(){
System.out.println("Samp106");
return "Richard Baldwin";
}//end displayName()
static int searchArray(
Object[] array, Object key){
return Arrays.binarySearch(
array,key);
}//end searchArray
//Following method displays result
// of the search
static void indexHandler(
int index, String key){
if(index >= 0){
System.out.println(key +
" is at index " + index );
}else{
System.out.println(key +
" is not in array");
}//end else
}//end index handler
}//end class Samp106Class
|
Program Samp108.java
/*File Samp108
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. This is a simple program for
students who dig deeply enough into the
Sun documentation to learn how to use
the asList() method of the Arrays
class. Otherwise, it will be a very
difficult problem.
The program gets a List view on an
array, modifies the List view, and
demonstrates that changes made to the
List write through to the underlying
array.
The output consists of the following
four lines of text:
Samp108
Richard Baldwin
Tom Dick Harry
Tom TOM Dick DICK Harry HARRY
**************************************/
import java.util.*;
class Samp108{
public static void main(
String[] args){
System.out.println(
Samp108Class.displayName());
//Create an array object of type
// Object. Populate it with refs
// to String objects.
Object[] arrayRef = {
"Tom","Dick","Harry"};
//Display the contents of the
// String object referred to by the
// elements of the array object
for(int cnt=0;cnt<arrayRef.length;
cnt++){
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();
//Get a List view of the array
// object
List listRef =
Samp108Class.getListView(
arrayRef);
//Get a ListIterator on the List
ListIterator iter =
listRef.listIterator();
//Use the ListIterator to modify
// the contents of the elements in
// the List
while(iter.hasNext()){
Object ref = iter.next();
//Note the required cast
iter.set(ref + " " +
((String)ref).toUpperCase());
}//end while
//Display the contents of the
// array. Note that the changes
// to the List have "written
// through" to the underlying
// array.
for(int cnt=0;cnt<arrayRef.length;
cnt++){
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();
}//end main
}//end class Samp108
//===================================//
class Samp108Class{
static String displayName(){
System.out.println("Samp108");
return "Richard Baldwin";
}//end displayName()
static List getListView(
Object[] array){
return Arrays.asList(array);
}//end getListView
}//end class Samp108Class
|
Program Samp110.java
/*File Samp110
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
Sorting strings in an array.
This is a very easy program for the
student who takes the time to dig
into the documentation and discover
the sort() method of the Arrays class.
It will be more difficult for students
who doesn't do that and attempt to
write their own sort routine.
The output of this program is as
follows:
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.
Bill is first
Samp110
Richard Baldwin
Bill Bill Joe Tom sue
Alice is first
Samp110
Richard Baldwin
Alice Bill Mike Mike mary
**************************************/
import java.util.*;
class Samp110{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = rGen.nextInt()%2;
String[] arrayRef = new String[5];
if(rNum == 0){
System.out.println(
"Bill is first");
arrayRef[0]="Joe";
arrayRef[1]="Bill";
arrayRef[2]="sue";
arrayRef[3]="Tom";
arrayRef[4]="Bill";
}else{
System.out.println(
"Alice is first");
arrayRef[0]="Mike";
arrayRef[1]="Bill";
arrayRef[2]="mary";
arrayRef[3]="Mike";
arrayRef[4]="Alice";
}//end else
Prob04Class.showYourName();
Prob04Class.sortArray(arrayRef);
for(int cnt=0;
cnt < arrayRef.length; cnt++){
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();
}//end main
}//end class Exam1Prob04
//===================================//
class Prob04Class{
static void showYourName(){
System.out.println("Samp110");
System.out.println(
"Richard Baldwin");
}//end showYourName()
static void sortArray(
String[] arrayRef){
Arrays.sort(arrayRef);
}//end sortArray()
}//end class Prob04Class
|
Program Samp116.java
/*File Samp116
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
The use of array objects containing
refs to other array objects,
The ability to copy data from one
array object to another,
The output consists of the following
seven lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. In all cases,
the four values and the arrangement of
those four values above the broken line
will match the four values and the
arrangement of the four values below
the broken line.
Samp116
Richard Baldwin
45 4
-17 -119
-------
45 4
-17 -119
**************************************/
import java.util.*;
public class Samp116 {
public static void main(
String[] args){
Samp116Class.displayYourName();
Random rGen =
new Random(new Date().getTime());
//Generate four random numbers and
// save them in a four-element
// array object of type int.
int[] rawData = new int[4];
for(int cnt=0;cnt<rawData.length;
cnt++){
rawData[cnt] =
(byte)rGen.nextInt();
System.out.print(
rawData[cnt] + " ");
if(cnt==1)System.out.println();
}//end for loop
System.out.println();
System.out.println("-------");
//Create two array objects of type
// int[], each containing two
// elements.
int[] refToIntArrayA = new int[2];
int[] refToIntArrayB = new int[2];
//Copy two values from the rawData
// array to each of the new two-
// element arrays.
System.arraycopy(
rawData,0,refToIntArrayA,0,2);
System.arraycopy(
rawData,2,refToIntArrayB,0,2);
//Create a two-element array of
// type int[][]. Populate each
// element with a reference to one
// of the two-element int arrays
// created and populated earlier.
int[][] refTo2dArray =
{refToIntArrayA,refToIntArrayB};
//Invoke a method that will
// display the values stored in
// each of the two-element int
// arrays whose references are
// stored in the two-element array
// of type int[][].
Samp116Class.displayArrayData(
refTo2dArray);
}//end main
}//end class Samp116
//===================================//
class Samp116Class{
public static void displayYourName(){
System.out.println("Samp116");
System.out.println(
"Richard Baldwin");
}//end displayYourName()
public static void displayArrayData(
int[][] refTo2dArray){
for(int j = 0;
j<refTo2dArray.length;j++){
for(int i=0;
i<refTo2dArray[j].length;i++){
System.out.print(
refTo2dArray[j][i] + " ");
}//end inner for loop
System.out.println();
}//end outer for loop
}//end displayArrayData()
}//end class Samp116Class
|
Program Samp118.java
/*File Samp118
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
The use of the generic type Object to
store a reference to an array
object,
The requirement to cast from Object
to int[] to access the data in the
array object stored as type Object.
The output consists of the following
seven lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. In all cases,
the four values and the arrangement of
those four values above the broken line
will match the four values and the
arrangement of the four values below
the broken line.
Samp118
Richard Baldwin
45 4
-17 -119
-------
45 4
-17 -119
**************************************/
import java.util.*;
public class Samp118 {
public static void main(
String[] args){
Samp118Class.displayYourName();
Random rGen =
new Random(new Date().getTime());
//Generate four random numbers and
// save them in a four-element
// array object of type int.
int[] rawData = new int[4];
for(int cnt=0;cnt<rawData.length;
cnt++){
rawData[cnt] =
(byte)rGen.nextInt();
System.out.print(
rawData[cnt] + " ");
if(cnt==1)System.out.println();
}//end for loop
System.out.println();
System.out.println("-------");
//Create two array objects of type
// int[], each containing two
// elements. Save refs to the
// array objects in ref vars of
// type Object. Note that these
// ref vars are not declared as
// type Object[].
Object refToIntArrayA = new int[2];
Object refToIntArrayB = new int[2];
//Copy two values from the rawData
// array to each of the new two-
// element arrays.
System.arraycopy(
rawData,0,refToIntArrayA,0,2);
System.arraycopy(
rawData,2,refToIntArrayB,0,2);
//Invoke a method that will
// display the values stored in
// one of the two-element int
// arrays whose reference is
// stored in a ref var of the
// type Object.
Samp118Class.displayArrayData(
refToIntArrayA);
//Do it again to display the other
// array.
Samp118Class.displayArrayData(
refToIntArrayB);
}//end main
}//end class Samp118
//===================================//
class Samp118Class{
public static void displayYourName(){
System.out.println("Samp118");
System.out.println(
"Richard Baldwin");
}//end displayYourName()
public static void displayArrayData(
Object refTypeObject){
//Note the following two rqmts to
// cast from type Object to
// type int[].
for(int j = 0;
j<((int[])refTypeObject).length;
j++){
System.out.print(
((int[])refTypeObject)[j]
+ " ");
}//for loop
System.out.println();
}//end displayArrayData()
}//end class Samp118Class
|
Program Samp120.java
/*File Samp120
Copyright 2001, R.G.Baldwin
Rev 11/30/01
Tested using JDK 1.3 under Win
Illustrates:
The use of array objects containing
refs to other array objects,
The ability to copy data from one
array object to another,
The use of the generic type Object to
store a reference to an array
object,
The requirement to cast from Object
to int[] to access the data in the
array object stored as type Object.
The output consists of the following
seven lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. In all cases,
the four values and the arrangement of
those four values above the broken line
will match the four values and the
arrangement of the four values below
the broken line.
Samp120
Richard Baldwin
45 4
-17 -119
-------
45 4
-17 -119
**************************************/
import java.util.*;
public class Samp120 {
public static void main(
String[] args){
Samp120Class.displayYourName();
Random rGen =
new Random(new Date().getTime());
//Generate four random numbers and
// save them in a four-element
// array object of type int.
int[] rawData = new int[4];
for(int cnt=0;cnt<rawData.length;
cnt++){
rawData[cnt] =
(byte)rGen.nextInt();
System.out.print(
rawData[cnt] + " ");
if(cnt==1)System.out.println();
}//end for loop
System.out.println();
System.out.println("-------");
//Create two array objects of type
// int[], each containing two
// elements. Save refs to the
// array objects in ref vars of
// type Object. Note that these
// ref vars are not declared as
// type Object[].
Object refToIntArrayA = new int[2];
Object refToIntArrayB = new int[2];
//Copy two values from the rawData
// array to each of the new two-
// element arrays.
System.arraycopy(
rawData,0,refToIntArrayA,0,2);
System.arraycopy(
rawData,2,refToIntArrayB,0,2);
//Create a two-element array of
// type Object[]. Populate each
// element with a reference to one
// of the two-element int arrays
// created and populated earlier.
Object[] refToObjArray =
{refToIntArrayA,refToIntArrayB};
//Invoke a method that will
// display the values stored in
// each of the two-element int
// arrays whose references are
// stored in the two-element array
// of type Object[].
new Samp120Class().
displayArrayData(refToObjArray);
}//end main
}//end class Samp120
//===================================//
class Samp120Class{
public static void displayYourName(){
System.out.println("Samp120");
System.out.println(
"Richard Baldwin");
}//end displayYourName()
public void displayArrayData(
Object[] refToObjArray){
for(int j = 0;
j<refToObjArray.length;j++){
//Note the following two rqmts to
// cast from type Object to
// type int[].
for(int i=0;
i<((int[])refToObjArray[j]).
length;i++){
System.out.print(
((int[])refToObjArray[j])[i]
+ " ");
}//end inner for loop
System.out.println();
}//end outer for loop
}//end displayArrayData()
}//end class Samp120Class
|
-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.
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.
-end-