Arrays and Classes

Introduction

As we have used them so far, array are primarily variables. This means that an array can be declared as a field in a class. To create a field as an array, you can declare it like a normal array in the body of the class. Here is an example:

public class CoordinateSystem {
    private int[] Points;
}

Like any field, when an array has been declared as a member variable, it is made available to all the other members of the same class. You can use this feature to initialize the array in one method and let other methods use the initialized variable. This also means that you do not have to pass the array as argument nor do you have to explicitly return it from a method.

After or when declaring an array, you must make sure you allocate memory for it prior to using it. Unlike C++, you can allocate memory for an array when declaring it. Here is an example:

public class CoordinateSystem {
    private int[] Points = new int[4];
}

You can also allocate memory for an array field in a constructor of the class. Here is an example:

public class CoordinateSystem {
    private int[] Points;

    public CoordinateSystem() {
        Points = new int[4];
    }
}

If you plan to use the array as soon as the program is running, you can initialize it using a constructor or a method that you know would be called before the array can be used. Here is an example:

public class CoordinateSystem {
    private int[] Points;

    public CoordinateSystem() {
        Points = new int[4];

        Points[0] = 2;
        Points[1] = 5;
        Points[2] = 2;
        Points[3] = 8;
    }
}

Practical LearningPractical Learning: Introducing Arrays and Classes

  1. Start NetBeans
  2. Create a Java Application named RentalProperties1
  3. To create a new class, in the Projects window, right-click RenatlProperties1 -> New -> Java Class…
  4. Set the Name to RentalProperty and press Enter
  5. Change the file as follows:
    package rentalproperties1;
    
    enum PropertyType {
        SINGLEFAMILY,
        TOWNHOUSE,
        APARTMENT,
        UNKNOWN };
                                   
    public class RentalProperty {
        private long[] propertyNumbers;
        private PropertyType[] types;
        private short[] bedrooms;
        private float[] bathrooms;
        private double[] monthlyRent;
    
        public RentalProperty() {
            propertyNumbers = new long[] {
                    192873, 498730, 218502, 612739,
                    457834, 927439, 570520, 734059 };
    
            types = new PropertyType[] {
                    PropertyType.SINGLEFAMILY, PropertyType.SINGLEFAMILY, 
                    PropertyType.APARTMENT, PropertyType.APARTMENT,
                    PropertyType.TOWNHOUSE, PropertyType.APARTMENT,
                    PropertyType.APARTMENT, PropertyType.TOWNHOUSE };
    
            bedrooms = new short[] { 5, 4, 2, 1, 3, 1, 3, 4 };
    
            bathrooms = new float[] { 3.50F, 2.50F, 1.00F, 1.00F,
                                          2.50F, 1.00F, 2.00F, 1.50F };
    
            monthlyRent = new double[] {
                    2250.00D, 1885.00D, 1175.50D, 945.00D,
                    1750.50D, 1100.00D, 1245.95D, 1950.25D };
        }            
    }

Presenting the Array

After an array has been created as a field, it can be used by any other member of the same class. Based on this, you can use a member of the same class to request values that would initialize it. You can also use another method to explore the array. Here is an example:

class CoordinateSystem {
    private int[] Points;

    public CoordinateSystem() {
        Points = new int[4];

        Points[0] = 2;
        Points[1] = -5;
        Points[2] = 2;
        Points[3] = 8;
    }

    public void showPoints() {
        System.out.println("Points Coordinates");
        System.out.println("P(" + Points[0] + ", " + Points[1] + ")");
        System.out.println("Q(" + Points[2] + ", " + Points[3] + ")");
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	CoordinateSystem coordinates = new CoordinateSystem();

        coordinates.showPoints();
    }
}

This would produce:

Points Coordinates
P(2, -5)
Q(2, 8)

Practical LearningPractical Learning: Presenting an Array

  1. To show the values of the array, change the file as follows:
    package rentalproperties1;
    
    enum PropertyType {
        SINGLEFAMILY,
        TOWNHOUSE,
        APARTMENT,
        UNKNOWN
    };
                                   
    public class RentalProperty {
        private long[] propertyNumbers;
        private PropertyType[] types;
        private short[] bedrooms;
        private float[] bathrooms;
        private double[] monthlyRent;
    
        public RentalProperty() {
            propertyNumbers = new long[] {
                    192873, 498730, 218502, 612739,
                    457834, 927439, 570520, 734059 };
    
            types = new PropertyType[] {
                    PropertyType.SINGLEFAMILY, PropertyType.SINGLEFAMILY, 
                    PropertyType.APARTMENT, PropertyType.APARTMENT,
                    PropertyType.TOWNHOUSE, PropertyType.APARTMENT,
                    PropertyType.APARTMENT, PropertyType.TOWNHOUSE };
    
            bedrooms = new short[] { 5, 4, 2, 1, 3, 1, 3, 4 };
    
            bathrooms = new float[] { 3.50F, 2.50F, 1.00F, 1.00F,
                                          2.50F, 1.00F, 2.00F, 1.50F };
    
            monthlyRent = new double[] {
                    2250.00D, 1885.00D, 1175.50D, 945.00D,
                    1750.50D, 1100.00D, 1245.95D, 1950.25D };
        }   
    
        public void showListing() {
            System.out.println("Properties Listing");
            System.out.println("=============================================");
            System.out.println("Prop #  Property Type  Beds Baths Monthly Rent");
            System.out.println("---------------------------------------------");
            for (int i = 0; i < 8; i++) {
                System.out.printf("%d\t%s\t%d   %.2f   %.2f\n",
                        propertyNumbers[i], types[i], bedrooms[i],
                        bathrooms[i], monthlyRent[i]);
            }
            System.out.println("=============================================");
        }         
    }
  2. Access the Main.java file and change it as follows:
    package rentalproperties1;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            RentalProperty property = new RentalProperty();
            property.showListing();
        }
    
    }
  3. Execute the application to see the result
    Properties Listing
    =============================================
    Prop #  Property Type  Beds Baths Monthly Rent
    ---------------------------------------------
    192873	SINGLEFAMILY	5   3.50   2250.00
    498730	SINGLEFAMILY	4   2.50   1885.00
    218502	APARTMENT	2   1.00   1175.50
    612739	APARTMENT	1   1.00   945.00
    457834	TOWNHOUSE	3   2.50   1750.50
    927439	APARTMENT	1   1.00   1100.00
    570520	APARTMENT	3   2.00   1245.95
    734059	TOWNHOUSE	4   1.50   1950.25
    =============================================

Arrays and Methods

Introduction

Each member of an array holds a legitimate value. Therefore, you can pass a single member of an array as argument. You can pass the name of the array variable with the accompanying index to a method.

The main purpose of using an array is to have access to various values grouped under one name. Still, an array is primarily a variable. As such, it can be passed to a method and it can be returned from a method.

Returning an Array From a Method

Like a normal variable, an array can be returned from a method. This means that the method would return a variable that carries various values. When declaring or defining the method, you must specify its data type. When the method ends, it would return an array represented by the name of its variable.

You can create a method that takes an array as argument and returns another array as argument.

To declare a method that returns an array, on the left of the method’s name, provide the type of value that the returned array will be made of, followed by empty square brackets. Here is an example:

public class CoordinateSystem {
    public int[] Initialize() {
    }
}

Remember that a method must always return an appropriate value depending on how it was declared. In this case, if it was specified as returning an array, then make sure it returns an array and not a regular value. One way you can do this is to declare and possibly initialize a local array variable. After using the local array, you return only its name (without the square brackets). Here is an example:

class CoordinateSystem {
    public int[] Initialize() {
        int[] Coords = new int[] { 12, 5, -2, -2 };

        return Coords;
    }
}

When a method returns an array, that method can be assigned to an array declared locally when you want to use it. Remember to initialize a variable with such a method only if the variable is an array.

Here is an example:

class CoordinateSystem {
    public int[] Initialize() {
        int[] Coords = new int[] { 12, 5, -2, -2 };

        return Coords;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	int[] System = new int[4];
        CoordinateSystem coordinates = new CoordinateSystem();

        System = coordinates.Initialize();
    }
}

The method could also be called as follows:

class CoordinateSystem {
    public int[] Initialize() {
        int[] Coords = new int[] { 12, 5, -2, -2 };

        return Coords;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
        CoordinateSystem coordinates = new CoordinateSystem();

	int[] System = coordinates.Initialize();
    }
}

If you initialize an array variable with a method that does not return an array, you would receive an error.

An Array Passed as Argument

Like a regular variable, an array can be passed as argument. To do this, in the parentheses of a method, provide the data type, the empty square brackets, and the name of the argument. Here is an example:

public class CoordinateSystem {
    public void showPoints(int[] Points) {
    }
}

When an array has been passed to a method, it can be used in the body of the method as any array can be, following the rules of array variables. For example, you can display its values. The simplest way you can use an array is to display the values of its members. This could be done as follows:

public class CoordinateSystem {
    public void showPoints(int[] Points) {
        System.out.println("Points Coordinates");
        System.out.println("P(" + Points[0] + ", " + Points[1] + ")");
        System.out.println("Q(" + Points[2] + ", " + Points[3] + ")");
    }
}

To call a method that takes an array as argument, simply type the name of the array in the parentheses of the called method. Here is an example:

class CoordinateSystem {
    public void showPoints(int[] Points) {
        System.out.println("Points Coordinates");
        System.out.println("P(" + Points[0] + ", " + Points[1] + ")");
        System.out.println("Q(" + Points[2] + ", " + Points[3] + ")");
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
        int Points[] = new int[] { -3, 3, 6, 3 };
        CoordinateSystem coordinates = new CoordinateSystem();

        coordinates.showPoints(Points);
    }
}

This would produce:

Points Coordinates
P(-3, 3)
Q(6, 3)

When an array is passed as argument to a method, the array is passed by reference. This means that, if the method makes any change to the array, the change would be kept when the method exits. You can use this characteristic to initialize an array from a method. Here is an example:

class CoordinateSystem {
    public void initialize(int[] coords) {
        coords[0] = -4;
        coords[1] = -2;
        coords[2] = -6;
        coords[3] =  3;
    }

    public void showPoints(int[] Points) {
        System.out.println("Points Coordinates");
        System.out.println("P(" + Points[0] + ", " + Points[1] + ")");
        System.out.println("Q(" + Points[2] + ", " + Points[3] + ")");
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
        int system[] = new int[4];
        CoordinateSystem coordinates = new CoordinateSystem();

        coordinates.initialize(system);
        coordinates.showPoints(system);
    }
}

This would produce:

Points Coordinates
P(-4, -2)
Q(-6, 3)

Notice that the initialize() method receives an un-initialized array but returns it with new values.

Instead of just one, you can create a method that receives more than one array and you can create a method that receives a combination of one or more arrays and one or more regular arguments. There is no rule that sets some restrictions.

You can also create a method that takes one or more arrays as argument(s) and returns a regular value of a primitive type.

The main() Method

Introduction

When a program starts, it looks for an entry point. This is the role of the main() method. In fact, a program, that is, an executable program, starts by, and stops with, the main() method. The way this works is that, at the beginning, the compiler looks for a method called main. If it does not find it, it produces an error. If it finds it, it enters the main() method in a top-down approach, starting just after the opening curly bracket. If it finds a problem and judges that it is not worth continuing, it stops and lets you know. If, or as long as, it does not find a problem, it continues line after line, with the option to even call or execute a method in the same file or in another file. This process continues to the closing curly bracket “}”. Once the compiler finds the closing bracket, the whole program has ended and stops.

If you want the user to provide information when executing your program, you can take care of this in the main() method. Consider the following code written in a file saved as Exercise.java:

public class Exercise {
    public static void main(String[] args) throws Exception {
	String firstName = "James";
     	String lastName  = "Weinberg";
        double weeklyHours = 36.50;
	double hourlySalary = 12.58;
	   
	String fullName = lastName + ", " + firstName;
	double weeklySalary = weeklyHours * hourlySalary;

	System.out.println("Employee Payroll");
	System.out.printf("Full Name:    %s\n", fullName);
	System.out.printf("WeeklySalary: %.2f", weeklySalary);
    }
}

To execute the application, at the Command Prompt and after Changing to the Directory that contains the file, you would type

C:\Exercise>javac Exercise.java

and press Enter. To execute the program, you would type the name Java Exercise and press Enter. The program would then prompt you for the information it needs.

Command Request from main()

To compile a program, at the command prompt, you would type javac, followed by the name of the file that contains main(), followed by the .java extension. Then, to execute a program, you would type the java command, followed by the name of the file. If you distribute a program, you would tell the user to type java followed by the name of the program at the command prompt. In some cases, you may want the user to type additional information besides the name of the program. To request additional information from the user, you can pass a String argument to the main()method. The argument should be passed as an array and make sure you provide a name for the argument. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        
    }
}

The reason you pass the argument as an array is so you can use as many values as you judge necessary. To provide values at the command prompt, the user types the name of the program followed by each necessary value. Here is an example:

Command Line

The values the user would provide are stored in a zero-based array without considering the name of the program. The first value (that is, after the name of the program) is stored at index 0, the second at index 1, etc. Based on this, the first argument is represented by args[0], the second is represented by args[1], etc.

Each of the values the user types is a string. If any one of them is not a string, you should convert/cast its string first to the appropriate value. Consider the following source code:

import java.io.*;

public class Exercise {
    public static void main(String[] args) throws Exception {
	String firstName;
     	String lastName;
        double weeklyHours;
	double hourlySalary;
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

	firstName    = args[0];
        lastName     = args[1];
        weeklyHours  = Double.parseDouble(args[2]);
	hourlySalary = Double.parseDouble(args[3]);

	String fullName = lastName + ", " + firstName;
	double weeklySalary = weeklyHours * hourlySalary;

	System.out.println("Employee Payroll");
	System.out.printf("Full Name:     %s\n", fullName);
	System.out.printf("Weekly Salary: %.2f\n", weeklySalary);
    }
}

To compile it at the Command Prompt, after switching to the directory that contains the file, you would type

javac Exercise.java

and press Enter. To execute the program, you would type Exercise followed by a first name, a last name, and two decimal values. An example would be Exercise Catherine Engolo 42.50 20.48

Command Prompt

An Array of Objects

Introduction

As done for primitive types, you can create an array of values where each member of the array is based on a formal class. Of course, you must have a class first. You can use one of the already available classes or you can create your own (class). Here is an example:

enum EmploymentStatus {
    FULLTIME,
    PARTTIME,
    UNKNOWN
};

class Employee {
    private long emplNbr;
    private String name;
    private EmploymentStatus st;
    private double wage;

    public long getEmployeeNumber() {
	return emplNbr;
    }
   
    public void setEmployeeNumber(long value) {
	emplNbr = value; 
    }

    public String getEmployeeName() {
	return name;
    }
    
    public void setEmployeeName(String value) {
	name = value; 
    }

    public EmploymentStatus getStatus() {
	return st;
    }

    public void setStatus(EmploymentStatus value) {
	st = value;
    }

    public double getHourlySalary() {
	return wage;
    }

    public void setHourlySalary(double value) {
	wage = value;
    }
}

Practical LearningPractical Learning: Introducing Arrays of Objects

  1. Create a new Java Application named RentalProperties2
  2. To create a new class, in the Projects window, right-click RenatlProperties2 -> New -> Java Class…
  3. Set the Name to RentalProperty and press Enter
  4. Change the file as follows:
    package rentalproperties2;
    
    enum PropertyType {
        SINGLEFAMILY,
        TOWNHOUSE,
        APARTMENT,
        UNKNOWN
    }
    
    public class RentalProperty {
        private long nbr;
        private PropertyType tp;
        private int bd;
        private float bt;
        private double rnt;
    
        public RentalProperty() {
            nbr = 0;
            tp = PropertyType.UNKNOWN;
            bd = 0;
            bt = 0.0F;
            rnt = 0D;
        }
    
        public RentalProperty(long propNbr, PropertyType type,
                              int beds, float baths, double rent) {
            nbr = propNbr;
            tp = type;
            bd = beds;
            bt = baths;
            rnt = rent;
        }
        
        public long getPropertyNumber() {
            return nbr;
        }
           
        public void setPropertyNumber(long propNumber) {
            nbr = propNumber;
        }
           
        public PropertyType getPropertyType() {
            return tp;
        }
           
        public void setPropertyType(PropertyType propType) {
            tp = propType;
        }
    
        public int getBedrooms() {
            return bd;
        }
           
        public void setBedrooms(int beds) {
            bd = beds;
        }
        
        public float getBathrooms() {
            return bt;
        }
           
        public void setBathrooms(float baths) {
            bt = baths;
        }
    
        public double getMonthlyRent() {
                return rnt;
        }
           
        public void setMonthlyRent(double value) {
            rnt = value;
        }
    }

Creating an Array of Objects

To create an array of objects, you can declare an array variable and use the square brackets to specify its size. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Employee[] staffMembers = new Employee[3];
    }
}

Initializing an Array of Objects

If you create an array like this, you can then access each member using its index, allocate memory for it using the new operator, then access each of its fields, still using its index, to assign it the desired value. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Employee[] staffMembers = new Employee[3];

        staffMembers[0] = new Employee();
        staffMembers[0].setEmployeeNumber(20204);
        staffMembers[0].setEmployeeName("Harry Fields");
        staffMembers[0].setStatus(EmploymentStatus.FULLTIME);
        staffMembers[0].setHourlySalary(16.85);

        staffMembers[1] = new Employee();
        staffMembers[1].setEmployeeNumber(92857);
        staffMembers[1].setEmployeeName("Jennifer Almonds");
        staffMembers[1].setStatus(EmploymentStatus.FULLTIME);
        staffMembers[1].setHourlySalary(22.25);

        staffMembers[2] = new Employee();
        staffMembers[2].setEmployeeNumber(42963);
        staffMembers[2].setEmployeeName("Sharon Culbritt");
        staffMembers[2].setStatus(EmploymentStatus.PARTTIME);
        staffMembers[2].setHourlySalary(10.95);
    }
}

As an alternative, you can also initialize each member of the array when creating it. To do this, before the semi-colon of creating the array, open the curly brackets, allocate memory for each member and specify the values of each field. To do this, you must use a constructor that takes each member you want to initialize, as argument. Here is an example:

enum EmploymentStatus {
    FULLTIME,
    PARTTIME,
    UNKNOWN
};

class Employee {
    private long emplNbr;
    private String name;
    private EmploymentStatus st;
    private double wage;

    public Employee() {
    }

    public Employee(long number, String name,
                    EmploymentStatus emplStatus,
		    double salary) {
        emplNbr = number;
        name = name;
        st = emplStatus;
        wage = salary;
    }

    public long getEmployeeNumber() {
	return emplNbr;
    }
   
    public void setEmployeeNumber(long value) {
	emplNbr = value; 
    }

    public String getEmployeeName() {
	return name;
    }
    
    public void setEmployeeName(String value) {
	name = value; 
    }

    public EmploymentStatus getStatus() {
	return st;
    }

    public void setStatus(EmploymentStatus value) {
	st = value;
    }

    public double getHourlySalary() {
	return wage;
    }

    public void setHourlySalary(double value) {
	wage = value;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Employee[] staffMembers = new Employee[] {
            new Employee(20204, "Harry Fields",
                         EmploymentStatus.FULLTIME,
                         16.85),

            new Employee(92857, "Jennifer Almonds",
                         EmploymentStatus.FULLTIME,
                         22.25),

            new Employee(42963, "Sharon Culbritt",
                         EmploymentStatus.PARTTIME,
                         10.95)
	};
    }
}

Accessing the Members of the Array

After creating and initializing the array, you can use it as you see fit. For example, you may want to display its values to the user. You can access any member of the array by its index, then use the same index to get its field(s) and consequently its (their) value(s). Here is an example:

enum EmploymentStatus {
    FULLTIME,
    PARTTIME,
    UNKNOWN
};

class Employee {
    private long emplNbr;
    private String name;
    private EmploymentStatus st;
    private double wage;

    public Employee() {
    }

    public Employee(long number, String name,
                    EmploymentStatus emplStatus,
		    double salary) {
        emplNbr = number;
        name = name;
        st = emplStatus;
        wage = salary;
    }

    public long getEmployeeNumber() {
	return emplNbr;
    }
   
    public void setEmployeeNumber(long value) {
	emplNbr = value; 
    }

    public String getEmployeeName() {
	return name;
    }
    
    public void setEmployeeName(String value) {
	name = value; 
    }

    public EmploymentStatus getStatus() {
	return st;
    }

    public void setStatus(EmploymentStatus value) {
	st = value;
    }

    public double getHourlySalary() {
	return wage;
    }

    public void setHourlySalary(double value) {
	wage = value;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Employee[] staffMembers = new Employee[3];

        staffMembers[0] = new Employee();
        staffMembers[0].setEmployeeNumber(20204);
        staffMembers[0].setEmployeeName("Harry Fields");
        staffMembers[0].setStatus(EmploymentStatus.FULLTIME);
        staffMembers[0].setHourlySalary(16.85);

        staffMembers[1] = new Employee();
        staffMembers[1].setEmployeeNumber(92857);
        staffMembers[1].setEmployeeName("Jennifer Almonds");
        staffMembers[1].setStatus(EmploymentStatus.FULLTIME);
        staffMembers[1].setHourlySalary(22.25);

        staffMembers[2] = new Employee();
        staffMembers[2].setEmployeeNumber(42963);
        staffMembers[2].setEmployeeName("Sharon Culbritt");
        staffMembers[2].setStatus(EmploymentStatus.PARTTIME);
        staffMembers[2].setHourlySalary(10.95);

	System.out.println("Employee Record");
        System.out.println("---------------------------");
	System.out.println("Employee #: " + staffMembers[1].getEmployeeNumber());
        System.out.println("Full Name:  " + staffMembers[1].getEmployeeName());
	System.out.println("Status:     " + staffMembers[1].getStatus());
        System.out.println("Salary:     " + staffMembers[1].getHourlySalary());
        System.out.println("---------------------------");
    }
}

This would produce:

Employee Record
---------------------------
Employee #: 92857
Full Name:  Jennifer Almonds
Status:     FULLTIME
Salary:     22.25
---------------------------

Once again, remember that the index you use must be higher than 0 but lower than the number of members – 1. Otherwise, the compiler would throw an ArrayIndexOutOfBoundsExceptionexception.

In the same way, you can use a for loop to access all members of the array using their index. Here is an example:

enum EmploymentStatus {
    FULLTIME,
    PARTTIME,
    UNKNOWN
};

class Employee {
    private long emplNbr;
    private String name;
    private EmploymentStatus st;
    private double wage;

    public Employee() {
    }

    public Employee(long number, String name,
                    EmploymentStatus emplStatus,
		    double salary) {
        emplNbr = number;
        name = name;
        st = emplStatus;
        wage = salary;
    }

    public long getEmployeeNumber() {
	return emplNbr;
    }
   
    public void setEmployeeNumber(long value) {
	emplNbr = value; 
    }

    public String getEmployeeName() {
	return name;
    }
    
    public void setEmployeeName(String value) {
	name = value; 
    }

    public EmploymentStatus getStatus() {
	return st;
    }

    public void setStatus(EmploymentStatus value) {
	st = value;
    }

    public double getHourlySalary() {
	return wage;
    }

    public void setHourlySalary(double value) {
	wage = value;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Employee[] staffMembers = new Employee[3];

        staffMembers[0] = new Employee();
        staffMembers[0].setEmployeeNumber(20204);
        staffMembers[0].setEmployeeName("Harry Fields");
        staffMembers[0].setStatus(EmploymentStatus.FULLTIME);
        staffMembers[0].setHourlySalary(16.85);

        staffMembers[1] = new Employee();
        staffMembers[1].setEmployeeNumber(92857);
        staffMembers[1].setEmployeeName("Jennifer Almonds");
        staffMembers[1].setStatus(EmploymentStatus.FULLTIME);
        staffMembers[1].setHourlySalary(22.25);

        staffMembers[2] = new Employee();
        staffMembers[2].setEmployeeNumber(42963);
        staffMembers[2].setEmployeeName("Sharon Culbritt");
        staffMembers[2].setStatus(EmploymentStatus.PARTTIME);
        staffMembers[2].setHourlySalary(10.95);

	System.out.println("Employee Record");
        System.out.println("---------------------------");
	for(int i = 0; i < 3; i++) {
	    System.out.println("Employee #: " + staffMembers[i].getEmployeeNumber());
            System.out.println("Full Name:  " + staffMembers[i].getEmployeeName());
	    System.out.println("Status:     " + staffMembers[i].getStatus());
            System.out.println("Salary:     " + staffMembers[i].getHourlySalary());
            System.out.println("---------------------------");
	}
    }
}

To access each member of the array, you can use the for each operator that allows you to use a name for each member and omit the square brackets. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Employee[] staffMembers = new Employee[3];

        staffMembers[0] = new Employee();
        staffMembers[0].setEmployeeNumber(20204);
        staffMembers[0].setEmployeeName("Harry Fields");
        staffMembers[0].setStatus(EmploymentStatus.FULLTIME);
        staffMembers[0].setHourlySalary(16.85);

        staffMembers[1] = new Employee();
        staffMembers[1].setEmployeeNumber(92857);
        staffMembers[1].setEmployeeName("Jennifer Almonds");
        staffMembers[1].setStatus(EmploymentStatus.FULLTIME);
        staffMembers[1].setHourlySalary(22.25);

        staffMembers[2] = new Employee();
        staffMembers[2].setEmployeeNumber(42963);
        staffMembers[2].setEmployeeName("Sharon Culbritt");
        staffMembers[2].setStatus(EmploymentStatus.PARTTIME);
        staffMembers[2].setHourlySalary(10.95);

	System.out.println("Employee Record");
        System.out.println("---------------------------");
	for(Employee empl : staffMembers) {
	    System.out.println("Employee #: " + empl.getEmployeeNumber());
            System.out.println("Full Name:  " + empl.getEmployeeName());
	    System.out.println("Status:     " + empl.getStatus());
            System.out.println("Salary:     " + empl.getHourlySalary());
            System.out.println("---------------------------");
	}
    }
}

This would produce:

Employee Record
---------------------------
Employee #: 20204
Full Name:  Harry Fields
Status:     FULLTIME
Salary:     16.85
---------------------------
Employee #: 92857
Full Name:  Jennifer Almonds
Status:     FULLTIME
Salary:     22.25
---------------------------
Employee #: 42963
Full Name:  Sharon Culbritt
Status:     PARTTIME
Salary:     10.95
---------------------------

Practical LearningPractical Learning: Using an Array of Objects

  1. Access the Main.java file and change it file as follows:
    package rentalproperties2;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            RentalProperty[] properties = new RentalProperty[8];
    
            properties[0] = new RentalProperty();
            properties[0].setPropertyNumber(192873);
            properties[0].setPropertyType(PropertyType.SINGLEFAMILY);
            properties[0].setBedrooms(5);
            properties[0].setBathrooms(3.50F);
            properties[0].setMonthlyRent(2250.00D);
    
            properties[1] = new RentalProperty();
            properties[1].setPropertyNumber(498730);
            properties[1].setPropertyType(PropertyType.SINGLEFAMILY);
            properties[1].setBedrooms(4);
            properties[1].setBathrooms(2.50F);
            properties[1].setMonthlyRent(1885.00D);
        
            properties[2] = new RentalProperty();
            properties[2].setPropertyNumber(218502);
            properties[2].setPropertyType(PropertyType.APARTMENT);
            properties[2].setBedrooms(2);
            properties[2].setBathrooms(1.00F);
            properties[2].setMonthlyRent(1175.50D);
    
            properties[3] = new RentalProperty();
            properties[3].setPropertyNumber(612739);
            properties[3].setPropertyType(PropertyType.APARTMENT);
            properties[3].setBedrooms(1);
            properties[3].setBathrooms(1.00F);
            properties[3].setMonthlyRent(945.00D);
        
            properties[4] = new RentalProperty();
            properties[4].setPropertyNumber(457834);
            properties[4].setPropertyType(PropertyType.TOWNHOUSE);
            properties[4].setBedrooms(3);
            properties[4].setBathrooms(2.50F);
            properties[4].setMonthlyRent(1750.50D);
            
            properties[5] = new RentalProperty();
            properties[5].setPropertyNumber(927439);
            properties[5].setPropertyType(PropertyType.APARTMENT);
            properties[5].setBedrooms(1);
            properties[5].setBathrooms(1.00F);
            properties[5].setMonthlyRent(1100.00D);
    
            properties[6] = new RentalProperty();
            properties[6].setPropertyNumber(570520);
            properties[6].setPropertyType(PropertyType.APARTMENT);
            properties[6].setBedrooms(3);
            properties[6].setBathrooms(2.00F);
            properties[6].setMonthlyRent(1245.95D);
        
            properties[7] = new RentalProperty();
            properties[7].setPropertyNumber(734059);
            properties[7].setPropertyType(PropertyType.TOWNHOUSE);
            properties[7].setBedrooms(4);
            properties[7].setBathrooms(1.50F);
            properties[7].setMonthlyRent(1950.25D);
    
            System.out.println("properties Listing");
            System.out.println("=============================================");
            System.out.println("Prop #  Property Type  Beds Baths Monthly Rent");
            System.out.println("---------------------------------------------");
            for (int i = 0; i < 8; i++) {
                System.out.printf("%d\t%s\t%d   %.2f   %.2f\n",
                                  properties[i].getPropertyNumber(),
                                  properties[i].getPropertyType(),
                                  properties[i].getBedrooms(),
                                  properties[i].getBathrooms(),
                                  properties[i].getMonthlyRent());   
            }
            System.out.println("=============================================");
        }        
    }
  2. Execute the application to see the result
    properties Listing
    =============================================
    Prop #  Property Type  Beds Baths Monthly Rent
    ---------------------------------------------
    192873	SINGLEFAMILY	5   3.50   2250.00
    498730	SINGLEFAMILY	4   2.50   1885.00
    218502	APARTMENT	2   1.00   1175.50
    612739	APARTMENT	1   1.00   945.00
    457834	TOWNHOUSE	3   2.50   1750.50
    927439	APARTMENT	1   1.00   1100.00
    570520	APARTMENT	3   2.00   1245.95
    734059	TOWNHOUSE	4   1.50   1950.25
    =============================================

A Class Array as a Field

Introduction

Like a primitive type, an array of objects can be made a field of a class. You can primarily declare the array and specify its size. Here is an example:

public class CompanyRecords {
    Employee[] Employees = new Employee[2];
}

After doing this, you can initialize the array from the index of each member. Alternatively, as we saw for field arrays of primitive types, you can declare the array in the body of the class, then use a constructor or another method of the class to allocate memory for it.

To initialize the array, remember that each member is a value whose memory must be allocated. Therefore, apply the new operator on each member of the array to allocate its memory, and then initialize it. Here is an example:

public class CompanyRecords {
    Employee[] Employees;

    public CompanyRecords() {
        Employees = new Employee[2];

        Employees[0] = new Employee();
        Employees[0].setEmployeeNumber(70128);
        Employees[0].setEmployeeName("Frank Dennison");
        Employees[0].setStatus(EmploymentStatus.PARTTIME);
        Employees[0].setHourlySalary(8.65);

        Employees[1] = new Employee();
        Employees[1].setEmployeeNumber(24835);
        Employees[1].setEmployeeName("Jeffrey Arndt");
        Employees[1].setStatus(EmploymentStatus.UNKNOWN);
        Employees[1].setHourlySalary(16.05);
    }
}

If the class used as field has an appropriate constructor, you can use it to initialize each member of the array. Here is an example:

class CompanyRecords {
    Employee[] Employees;

    public CompanyRecords() {
        Employees = new Employee[] {
	    new Employee(70128, "Frank Dennison",
			 EmploymentStatus.PARTTIME, 8.65),
	    new Employee(24835, "Jeffrey Arndt",
			 EmploymentStatus.UNKNOWN, 16.05)
	};
    }
}

Using the Array

Once you have created and initialized the array, you can use it as you see fit, such as displaying its values to the user. You must be able to access each member of the array, using its index. Once you have accessed a member, you can get to its fields or methods. Here is an example:

enum EmploymentStatus {
    FULLTIME,
    PARTTIME,
    UNKNOWN
};

class Employee {
    private long emplNbr;
    private String name;
    private EmploymentStatus st;
    private double wage;

    public Employee() {
    }

    public Employee(long number, String name,
                    EmploymentStatus emplStatus,
		    double salary) {
        emplNbr = number;
        name = name;
        st = emplStatus;
        wage = salary;
    }

    public long getEmployeeNumber() {
	return emplNbr;
    }
   
    public void setEmployeeNumber(long value) {
	emplNbr = value; 
    }

    public String getEmployeeName() {
	return name;
    }
    
    public void setEmployeeName(String value) {
	name = value; 
    }

    public EmploymentStatus getStatus() {
	return st;
    }

    public void setStatus(EmploymentStatus value) {
	st = value;
    }

    public double getHourlySalary() {
	return wage;
    }

    public void setHourlySalary(double value) {
	wage = value;
    }
}

class CompanyRecords {
    Employee[] Employees;

    public CompanyRecords() {
        Employees = new Employee[4];

        Employees[0] = new Employee();
        Employees[0].setEmployeeNumber(70128);
        Employees[0].setEmployeeName("Frank Dennison");
        Employees[0].setStatus(EmploymentStatus.PARTTIME);
        Employees[0].setHourlySalary(8.65);

        Employees[1] = new Employee();
        Employees[1].setEmployeeNumber(24835);
        Employees[1].setEmployeeName("Jeffrey Arndt");
        Employees[1].setStatus(EmploymentStatus.UNKNOWN);
        Employees[1].setHourlySalary(16.05);

        Employees[2] = new Employee();
        Employees[2].setEmployeeNumber(92735);
        Employees[2].setEmployeeName("Nathan Sanitrah");
        Employees[2].setStatus(EmploymentStatus.FULLTIME);
        Employees[2].setHourlySalary(8.65);

        Employees[3] = new Employee();
        Employees[3].setEmployeeNumber(29385);
        Employees[3].setEmployeeName("Olivia Hathay");
        Employees[3].setStatus(EmploymentStatus.FULLTIME);
        Employees[3].setHourlySalary(16.05);
    }

    public void showRecords() {
        System.out.println("Employees Records");
        System.out.println("==========================");

        for (Employee member : Employees) {
            System.out.printf("Employee #: %d\n", member.getEmployeeNumber());
            System.out.printf("Full Name:  %s\n", member.getEmployeeName());
            System.out.printf("Status:     %s\n", member.getStatus());
            System.out.printf("Hourly Wage %.2f\n", member.getHourlySalary());
            System.out.println("---------------------------");
        }
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	CompanyRecords Records = new CompanyRecords();
        Records.showRecords();
    }
}

This would produce:

Employees Records
==========================
Employee #: 70128
Full Name:  Frank Dennison
Status:     PARTTIME
Hourly Wage 8.65
---------------------------
Employee #: 24835
Full Name:  Jeffrey Arndt
Status:     UNKNOWN
Hourly Wage 16.05
---------------------------
Employee #: 92735
Full Name:  Nathan Sanitrah
Status:     FULLTIME
Hourly Wage 8.65
---------------------------
Employee #: 29385
Full Name:  Olivia Hathay
Status:     FULLTIME
Hourly Wage 16.05
---------------------------

Arrays of Objects and Methods

Passing an Array of Objects as Argument

As done for an array of a primitive type, you can pass an array of objects as arguments. You follow the same rules we reviewed. That is, in the parentheses of a method, enter the class name, the empty square brackets, and the name of the argument. Here is an example:

public class CompanyRecords {
    public CompanyRecords(Employee[] Employees) {
    }
}

You can then access each member of the argument and do what you judge necessary. For example, you can initialize the array. To call a method that takes an array of objects, in its parentheses, just enter the name of the array. Here is an example:

class CompanyRecords {

    public CompanyRecords(Employee[] employees) {
        employees = new Employee[4];

        employees[0] = new Employee();
        employees[0].setEmployeeNumber(70128);
        employees[0].setEmployeeName("Frank Dennison");
        employees[0].setStatus(EmploymentStatus.PARTTIME);
        employees[0].setHourlySalary(8.65);

        employees[1] = new Employee();
        employees[1].setEmployeeNumber(24835);
        employees[1].setEmployeeName("Jeffrey Arndt");
        employees[1].setStatus(EmploymentStatus.UNKNOWN);
        employees[1].setHourlySalary(16.05);

        employees[2] = new Employee();
        employees[2].setEmployeeNumber(92735);
        employees[2].setEmployeeName("Nathan Sanitrah");
        employees[2].setStatus(EmploymentStatus.FULLTIME);
        employees[2].setHourlySalary(8.65);

        employees[3] = new Employee();
        employees[3].setEmployeeNumber(29385);
        employees[3].setEmployeeName("Olivia Hathay");
        employees[3].setStatus(EmploymentStatus.FULLTIME);
        employees[3].setHourlySalary(16.05);
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
        Employee[] values = new Employee[4];
	CompanyRecords Records = new CompanyRecords(values);
    }
}

As stated for an array of primitive type, an array of objects passed as argument is treated as a reference. You can use this characteristic of arrays to initialize the array.

Practical LearningPractical Learning: Passing an Array of Objects as Argument

  1. Access the Main.java file and change it file as follows:
    package rentalproperties2;
    
    public class Main {
        private static void showProperties(RentalProperty[] props) {
            System.out.println("properties Listing");
            System.out.println("=============================================");
            System.out.println("Prop #  Property Type  Beds Baths Monthly Rent");
            System.out.println("---------------------------------------------");
            for (int i = 0; i < props.length; i++) {
                System.out.printf("%d\t%s\t%d   %.2f   %.2f\n",
                                  props[i].getPropertyNumber(),
                                  props[i].getPropertyType(),
                                  props[i].getBedrooms(),
                                  props[i].getBathrooms(),
                                  props[i].getMonthlyRent());   
            }
            System.out.println("=============================================");    
        }
            
        public static void main(String[] args) throws Exception {
            RentalProperty[] properties = new RentalProperty[8];
    
            properties[0] = new RentalProperty();
            properties[0].setPropertyNumber(192873);
            properties[0].setPropertyType(PropertyType.SINGLEFAMILY);
            properties[0].setBedrooms(5);
            properties[0].setBathrooms(3.50F);
            properties[0].setMonthlyRent(2250.00D);
    
            properties[1] = new RentalProperty();
            properties[1].setPropertyNumber(498730);
            properties[1].setPropertyType(PropertyType.SINGLEFAMILY);
            properties[1].setBedrooms(4);
            properties[1].setBathrooms(2.50F);
            properties[1].setMonthlyRent(1885.00D);
        
            properties[2] = new RentalProperty();
            properties[2].setPropertyNumber(218502);
            properties[2].setPropertyType(PropertyType.APARTMENT);
            properties[2].setBedrooms(2);
            properties[2].setBathrooms(1.00F);
            properties[2].setMonthlyRent(1175.50D);
    
            properties[3] = new RentalProperty();
            properties[3].setPropertyNumber(612739);
            properties[3].setPropertyType(PropertyType.APARTMENT);
            properties[3].setBedrooms(1);
            properties[3].setBathrooms(1.00F);
            properties[3].setMonthlyRent(945.00D);
        
            properties[4] = new RentalProperty();
            properties[4].setPropertyNumber(457834);
            properties[4].setPropertyType(PropertyType.TOWNHOUSE);
            properties[4].setBedrooms(3);
            properties[4].setBathrooms(2.50F);
            properties[4].setMonthlyRent(1750.50D);
            
            properties[5] = new RentalProperty();
            properties[5].setPropertyNumber(927439);
            properties[5].setPropertyType(PropertyType.APARTMENT);
            properties[5].setBedrooms(1);
            properties[5].setBathrooms(1.00F);
            properties[5].setMonthlyRent(1100.00D);
    
            properties[6] = new RentalProperty();
            properties[6].setPropertyNumber(570520);
            properties[6].setPropertyType(PropertyType.APARTMENT);
            properties[6].setBedrooms(3);
            properties[6].setBathrooms(2.00F);
            properties[6].setMonthlyRent(1245.95D);
        
            properties[7] = new RentalProperty();
            properties[7].setPropertyNumber(734059);
            properties[7].setPropertyType(PropertyType.TOWNHOUSE);
            properties[7].setBedrooms(4);
            properties[7].setBathrooms(1.50F);
            properties[7].setMonthlyRent(1950.25D);
    
            showProperties(properties);
        }        
    }
  2. Execute the application to see the result

Returning an Array of Objects

An array of objects can be returned from a method. To indicate this when defining the method, first type the name of the class followed by square brackets. Here is an example:

public class CompanyRecords {
    public Employee[] registerEmployees() {
    }
}

In the body of the method, you can take care of any assignment you want. The major rule to follow is that, before exiting the method, you must return an array of the class indicated on the left side of the method name.

To use the method, you can simply call it. If you want, since the method returns an array, you can retrieve that series and store it in a local array for later use. Here is an example:

enum EmploymentStatus {
    FULLTIME,
    PARTTIME,
    UNKNOWN
};

class Employee {
    private long emplNbr;
    private String name;
    private EmploymentStatus st;
    private double wage;

    public Employee() {
    }

    public Employee(long number, String name,
                    EmploymentStatus emplStatus,
		    double salary) {
        emplNbr = number;
        name = name;
        st = emplStatus;
        wage = salary;
    }

    public long getEmployeeNumber() {
	return emplNbr;
    }
   
    public void setEmployeeNumber(long value) {
	emplNbr = value; 
    }

    public String getEmployeeName() {
	return name;
    }
    
    public void setEmployeeName(String value) {
	name = value; 
    }

    public EmploymentStatus getStatus() {
	return st;
    }

    public void setStatus(EmploymentStatus value) {
	st = value;
    }

    public double getHourlySalary() {
	return wage;
    }

    public void setHourlySalary(double value) {
	wage = value;
    }
}

class CompanyRecords {

    public CompanyRecords() {
    }

    public Employee[] registerEmployees() {
        Employee[] employees = new Employee[5];
        employees[0] = new Employee();
        employees[0].setEmployeeNumber(20062);
        employees[0].setEmployeeName("Robert Mathews");
        employees[0].setStatus(EmploymentStatus.FULLTIME);
        employees[0].setHourlySalary(8.65);

        employees[1] = new Employee();
        employees[1].setEmployeeNumber(92741);
        employees[1].setEmployeeName("Helena Orlo");
        employees[1].setStatus(EmploymentStatus.FULLTIME);
        employees[1].setHourlySalary(16.05);

        employees[2] = new Employee();
        employees[2].setEmployeeNumber(81824);
        employees[2].setEmployeeName("Rosette Bitha");
        employees[2].setStatus(EmploymentStatus.PARTTIME);
        employees[2].setHourlySalary(8.65);

        employees[3] = new Employee();
        employees[3].setEmployeeNumber(28024);
        employees[3].setEmployeeName("Julius Nye");
        employees[3].setStatus(EmploymentStatus.UNKNOWN);
        employees[3].setHourlySalary(16.05);

        employees[4] = new Employee();
        employees[4].setEmployeeNumber(19283);
        employees[4].setEmployeeName("Frank Arnolds");
        employees[4].setStatus(EmploymentStatus.FULLTIME);
        employees[4].setHourlySalary(16.05);

	return employees;
    }

    public void showRecords(Employee[] records) {
        System.out.println("Employees Records");
        System.out.println("==========================");

        for (Employee eachOne : records) {
            System.out.printf("Employee #: %d\n", eachOne.getEmployeeNumber());
            System.out.printf("Full Name:  %s\n", eachOne.getEmployeeName());
            System.out.printf("Status:     %s\n", eachOne.getStatus());
            System.out.printf("Hourly Wage %.2f\n", eachOne.getHourlySalary());
            System.out.println("---------------------------");
        }
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
        CompanyRecords people = new CompanyRecords();

        Employee[] contractors = people.registerEmployees();
        people.showRecords(contractors);
    }
}

Practical LearningPractical Learning: Returning an Array of Objects

  1. To return an array from a method, change the file as follows:
    package rentalproperties2;
    
    public class Main {
        private static RentalProperty[] createProperties() {
            RentalProperty[] records = new RentalProperty[8];
    
            records[0] = new RentalProperty();
            records[0].setPropertyNumber(192873);
            records[0].setPropertyType(PropertyType.SINGLEFAMILY);
            records[0].setBedrooms(5);
            records[0].setBathrooms(3.50F);
            records[0].setMonthlyRent(2250.00D);
    
            records[1] = new RentalProperty();
            records[1].setPropertyNumber(498730);
            records[1].setPropertyType(PropertyType.SINGLEFAMILY);
            records[1].setBedrooms(4);
            records[1].setBathrooms(2.50F);
            records[1].setMonthlyRent(1885.00D);
        
            records[2] = new RentalProperty();
            records[2].setPropertyNumber(218502);
            records[2].setPropertyType(PropertyType.APARTMENT);
            records[2].setBedrooms(2);
            records[2].setBathrooms(1.00F);
            records[2].setMonthlyRent(1175.50D);
    
            records[3] = new RentalProperty();
            records[3].setPropertyNumber(612739);
            records[3].setPropertyType(PropertyType.APARTMENT);
            records[3].setBedrooms(1);
            records[3].setBathrooms(1.00F);
            records[3].setMonthlyRent(945.00D);
        
            records[4] = new RentalProperty();
            records[4].setPropertyNumber(457834);
            records[4].setPropertyType(PropertyType.TOWNHOUSE);
            records[4].setBedrooms(3);
            records[4].setBathrooms(2.50F);
            records[4].setMonthlyRent(1750.50D);
            
            records[5] = new RentalProperty();
            records[5].setPropertyNumber(927439);
            records[5].setPropertyType(PropertyType.APARTMENT);
            records[5].setBedrooms(1);
            records[5].setBathrooms(1.00F);
            records[5].setMonthlyRent(1100.00D);
    
            records[6] = new RentalProperty();
            records[6].setPropertyNumber(570520);
            records[6].setPropertyType(PropertyType.APARTMENT);
            records[6].setBedrooms(3);
            records[6].setBathrooms(2.00F);
            records[6].setMonthlyRent(1245.95D);
        
            records[7] = new RentalProperty();
            records[7].setPropertyNumber(734059);
            records[7].setPropertyType(PropertyType.TOWNHOUSE);
            records[7].setBedrooms(4);
            records[7].setBathrooms(1.50F);
            records[7].setMonthlyRent(1950.25D);
            
            return records;
        }
        
        private static void showProperties(RentalProperty[] props) {
            System.out.println("Properties Listing");
            System.out.println("=============================================");
            System.out.println("Prop #  Property Type  Beds Baths Monthly Rent");
            System.out.println("---------------------------------------------");
            for (int i = 0; i < props.length; i++) {
                System.out.printf("%d\t%s\t%d   %.2f   %.2f\n",
                                  props[i].getPropertyNumber(),
                                  props[i].getPropertyType(),
                                  props[i].getBedrooms(),
                                  props[i].getBathrooms(),
                                  props[i].getMonthlyRent());   
            }
            System.out.println("=============================================");    
        }
            
        public static void main(String[] args) throws Exception {
            RentalProperty[] properties = createProperties();
    
            showProperties(properties);
        }        
    }
  2. Execute the application to see the result
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: