Monthly Archives: July 2011

The Java Terminology

Java is a programming language and a platform to develop and run software applications.

It comes in different flavors:

  1. Java Standard Edition (Java SE)
    This is the plain vanilla version of Java. You can implement any software application with it. Java SE has a large library of code which includes many reusable software functions. Java EE and Java ME described below are built on top of Java SE.
  2. Java Enterprise Edition (Java EE)
    This flavor of Java builds on Java SE. Java EE contains additional libraries of code and development tools that are uniquely useful in developing business applications.
  3. Java Micro Edition (Java ME)
    Than being yet another extension to Java SE, this is in fact a reduced version of Java SE and an associated library of software that addresses the unique needs of Java applications that should run on limited capability devices like mobile phones and PDAs

Exceptional Handling

This code takes an integer input from the user. If the user inputs a number, the entered number shall be displayed to the user. If user input anything unexpected then the program will terminate with the error regarding invalid entrty.

package com.gl;

import java.util.Scanner;

public class exceptionHandling {
	
	public static void main(String [] args)
	{
		try
		{
			int a;
			System.out.print("Please enter a number:");
			Scanner x=new Scanner (System.in);
			a=x.nextInt();
			System.out.println("The number you entered was:"+a);
		}
		catch (Exception e)
		{
			System.out.println("This program will terminate. Invalid Number!");
		}
		
	}

}

B.java

Advanced Concepts Used: Inheritance and Function Overriding
Observation: It has been observed that when the function add in A was overridden by class B then calling the function directly from Excercise class runs the original function.


Excercise.java
This code develops two objects one for class A and another object class B.

<strong></strong>package com.gl;
public class Exercise {
public static void main(String args [])
{
B x= new B();
x.run();
A xx= new A();
xx.a=10;
xx.b=20;
System.out.println(xx.add());
System.out.println(x.add());


}



}


<strong>A.java
</strong>Just defines four basic mathematical operation.

<strong></strong>
package com.gl;

public class A {

int a,b;
int add()
{
return a+b;
}
int sub()
{
return a-b;
}
int mul()
{
return a*b;
}


}


B.java
This class inherits function of class A and then does function overriding.

package com.gl;
//inheritance
public class B extends A {

//function overriding
int add()
{
return a-b;
}
void run()
{
a=5;
b=10;
System.out.println(add());
}

}

A.java


package com.gl;

public class A {

int a,b;
int add()
{
return a+b;
}
int sub()
{
return a-b;
}
int mul()
{
return a*b;
}
static int div()
{
return a/b;
}

}

File Processing

Files

Introduction

File processing is performed in Java using various classes. The primary class used to handle files is called File. The File class is part of the java.iopackage. To use it, you can start by importing it in your file. Here is an example:

import java.io.File;

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

The File class is based on (implements) the FileOutputStream class. The FileOutputStream class is based on the OutputStream class. That is how it gets most of its functionality.

To use a file, declare a File variable using one of its constructors. One of the constructors takes one argument as a string, the name of the file or its complete path. Of course, if the file has an extension, you must include it. Here is an example:

import java.io.File;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	File fleExample = new File("Example.xpl");
    }
}

The only real thing the File class does is to indicate that you are planning to use a file. It does not indicate what you will do with the file. You must specify whether you will create a new file or open an existing one.

Practical LearningPractical Learning: Introducing File Processing

  1. Start NetBeans
  2. To create a Java Application, on the main menu, click File -> New Project…
  3. Select Java Application and click Next
  4. Set the Name to StudentUniversity1
  5. Set the Main Class name to Central
  6. Click Finish
  7. In the Projects window, right-click StudentUniversity1 -> New -> Java Package…
  8. Set the name to Students
  9. Click Finish
  10. To create a new class, in the Projects window, under StudentUniversity1, right-click Students -> New -> Java Class…
  11. Set the Name to Student
  12. Click Finish
  13. Change the file as follows:
    package Students;
    
    public class Student {
        public int StudentIdentificationNumber;
        public String FirstName;
        public String LastName;
        public int CreditsSoFar;
        public double GPA;
    }

Creating a File

If you want to create a new file, you must use a class that is equipped to write values to a file. To do this, you can use the PrintWriter class. The PrintWriter class is defined in the java.io package. Therefore, if you want to use it, you can import it in your document. This would be done as follows:

import java.io.PrintWriter;

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

    }
}

The PrintWriter class is based on (implements) the Writer class. The class is equipped with the necessary means of writing values to a file.

Before using the class, declare a variable for it. This class is equipped with many constructors. One of the constructors takes as argument an OutputStream object. We saw that the File class is based on OutputStream. This means that you can pass a File object to a PrintWriter constructor. This would be done as follows:

import java.io.File;
import java.io.PrintWriter;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to use a file
	File fleExample = new File("Example.xpl");
        // Create that file and prepare to write some values to it
        PrintWriter pwInput = new PrintWriter(fleExample);
    }
}

Writing to a File

After creating a PrintWriter object, you can write values to the file. To support this, thePrintWriter class is equipped with the print() and println() methods that is overloaded with various versions for each type of values (boolean, char, char[], int, float, double, String, orObject). Therefore, to write a value to a file, call the appropriate version of the PrintWriter.print()method and pass the desired value. Here are examples:

import java.io.File;
import java.io.PrintWriter;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to use a file
	File fleExample = new File("Example.xpl");
        // Create that file and prepare to write some values to it
        PrintWriter pwInput = new PrintWriter(fleExample);

	// Write a string to the file
	pwInput.println("Francine");
	// Write a string to the file
     	pwInput.println("Mukoko");
	// Write a double-precision number to the file
	pwInput.println(22.85);
	// Write a Boolean value to the file
	pwInput.print(true);
    }
}

After using a PrintWriter object, you should free the resources it was using. To assist you with this, the PrintWriter class is equipped with the Close() method. Here is an example of calling:

import java.io.File;
import java.io.PrintWriter;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to use a file
	File fleExample = new File("Example.xpl");
        // Create that file and prepare to write some values to it
        PrintWriter pwInput = new PrintWriter(fleExample);

	// Write a string to the file
	pwInput.println("Francine");
	// Write a string to the file
     	pwInput.println("Mukoko");
	// Write a double-precision number to the file
	pwInput.println(22.85);
	// Write a Boolean value to the file
	pwInput.print(true);
	
        // After using the PrintWriter object, de-allocated its memory
        pwInput.close();
        // For convenience, let the user know that the file has been created
        System.out.println("The file has been created.");   
    }
}

Practical LearningPractical Learning: Creating a File

  1. Click the Central.java tab
  2. Change the file as follows:
    package studentuniversity1;
    import java.io.*;
    import Students.Student;
    import java.util.Scanner;
    
    public class Central {
        public static Student register() {
            Student kid = new Student();
            Scanner scnr = new Scanner(System.in);
            
            System.out.println("Enter information about the student");
            System.out.print("Student ID: ");
            kid.StudentIdentificationNumber = scnr.nextInt();
            System.out.print("First Name: ");
            kid.FirstName = scnr.next();
            System.out.print("Last Name: ");
            kid.LastName = scnr.next();
            System.out.print("Number of credits so far: ");
            kid.CreditsSoFar = scnr.nextInt();
            System.out.print("Grade point average: ");
            kid.GPA = scnr.nextDouble();
            
            return kid;
        }
    
        public static void save(Student pupil) throws Exception {
            String strFilename = "";
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the file name: ");
            strFilename = scnr.next();
            
            // Make sure the user entered a valid file name
            if( !strFilename.equals("")) {
                // Indicate that you are planning to use a file
                File fleExample = new File(strFilename);
                // Create that file and prepare to write some values to it
                PrintWriter wrtStudent = new PrintWriter(fleExample);
    
                wrtStudent.println(pupil.StudentIdentificationNumber);
                wrtStudent.println(pupil.FirstName);
                wrtStudent.println(pupil.LastName);
                wrtStudent.println(pupil.CreditsSoFar);
                wrtStudent.println(pupil.GPA);
                
                // After using the PrintWriter object, de-allocated its memory
                wrtStudent.close();
                // For convenience, let the user know that the file has been created
                System.out.println("The file has been created.");
            }
        }
        
        public static void show(Student std) throws Exception {
            System.out.println("Student Record");
            System.out.println("Student ID: " + std.StudentIdentificationNumber);
            System.out.println("First Name: " + std.FirstName);
            System.out.println("Last Name: " + std.LastName);
            System.out.println("Number of credits so far: " + std.CreditsSoFar);
            System.out.println("Grade point average: " + std.GPA);
        }
        
        public static void main(String[] args) throws Exception {
            String answer = "n";
            Student std = register();
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Do you want to save this information (y/n)? ");
            answer = scnr.next();
            
            if( (answer.equals("y")) || (answer.equals("Y")) ) {
    	    show(std);
                save(std);
            }
        }
    
    }
  3. Press F6 to execute the application
  4. Enter the following information:

    Student ID:
    927426

    First Name:
    Christopher

    Last Name
    Lame

    Credits so far:
    38

    GPA
    2.26

  5. When asked whether you want to save, click Yes
  6. Type Student1.txt as the file name and press Enter
  7. Execute the application again
  8. Enter the following information:

    Student ID:
    286350

    First Name:
    June

    Last Name
    Glasnow

    Credits so far:
    69

    GPA
    3.15

  9. When asked whether you want to save, click Yes
  10. Type Student2.txt as the file name and press Enter

Opening a File

Besides creating a file, the second most common operation performed on a file consists of opening one. You can open a file using the File class. As done previously, first declare a File variable and pass the name of the file to its constructor. Here is an example:

import java.io.File;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Incidate that you are planning to opena file
	File fleExample = new File("Example.xpl");
    }
}

Reading From a File

To support the ability to read a value from a file, you can use the Scanner class. To support this operation, the Scanner class is equipped with a constructor that takes a File object as argument. Therefore, you can pass it a File variable you will have previously declared. Here is an example of declaring and initializing a variable for it:

import java.io.File;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to opena file
	File fleExample = new File("Example.xpl");
        // Prepare a Scanner that will "scan" the document
        Scanner opnScanner = new Scanner(fleExample);
    }
}

The values of a file are stored in or more lines. To continuously read the lines from the file, one at a time, you can use a while loop. In the while loop, continuously use the Scanner object that can read a line of value(s). In the while statement, to check whether the Scanner object has not gotten to the last line, you can check the status of its hasNext() method. As long as this method returns true, the Scanner reader has not gotten to the end of the file. Once the Scanner object has arrived to the end, this method would return false. Here is an example of implementing this scenario:

import java.io.File;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to opena file
	File fleExample = new File("Example.xpl");
        // Prepare a Scanner that will "scan" the document
        Scanner opnScanner = new Scanner(fleExample);

	// Read each line in the file
        while(opnScanner.hasNext()) {
            // Read each line and display its value
	    System.out.println("First Name:    " + opnScanner.nextLine());
	    System.out.println("Last Name:     " + opnScanner.nextLine());
	    System.out.println("Hourly Salary: " + opnScanner.nextLine());
	    System.out.println("Is Full Time?: " + opnScanner.nextLine());
	}
    }
}

After using the Scanner object, to free the resources it was using, call its close() method. Here is an example:

import java.io.File;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to opena file
	File fleExample = new File("Example.xpl");
        // Prepare a Scanner that will "scan" the document
        Scanner opnScanner = new Scanner(fleExample);

	// Read each line in the file
        while( opnScanner.hasNext() ) {
            // Read each line and display its value
	    System.out.println("First Name:    " + opnScanner.nextLine());
	    System.out.println("Last Name:     " + opnScanner.nextLine());
	    System.out.println("Hourly Salary: " + opnScanner.nextLine());
	    System.out.println("Is Full Time?: " + opnScanner.nextLine());
	}
            
    	// De-allocate the memory that was used by the scanner
        opnScanner.close();
    }
}

Practical LearningPractical Learning: Opening a File

  1. Change the Central.java file as follows:
    package studentuniversity1;
    import java.io.*;
    import Students.Student;
    import java.util.Scanner;
    
    public class Main {
        public static Student register() {
            Student kid = new Student();
            Scanner scnr = new Scanner(System.in);
            
            System.out.println("Enter information about the student");
            System.out.print("Student ID: ");
            kid.StudentIdentificationNumber = scnr.nextInt();
            System.out.print("First Name: ");
            kid.FirstName = scnr.next();
            System.out.print("Last Name: ");
            kid.LastName = scnr.next();
            System.out.print("Number of credits so far: ");
            kid.CreditsSoFar = scnr.nextInt();
            System.out.print("Grade point average: ");
            kid.GPA = scnr.nextDouble();
            
            return kid;
        }
    
        public static void save(Student pupil) throws Exception {
            String strFilename = "";
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the file name: ");
            strFilename = scnr.next();
            
            // Make sure the user entered a valid file name
            if( !strFilename.equals("")) {
                // Incidate that you are planning to use a file
                File fleStudent = new File(strFilename);
                // Create that file and prepare to write some values to it
                PrintWriter wrtStudent = new PrintWriter(fleStudent);
    
                wrtStudent.println(pupil.StudentIdentificationNumber);
                wrtStudent.println(pupil.FirstName);
                wrtStudent.println(pupil.LastName);
                wrtStudent.println(pupil.CreditsSoFar);
                wrtStudent.println(pupil.GPA);
                
                // After using the PrintWriter object, de-allocated its memory
                wrtStudent.close();
                // For convenience, let the user know that the file has been created
                System.out.println("The file has been created.");
            }
        }
        
        public static Student open()  throws Exception {
            String strFilename = "";
            String strStudentIdentificationNumber;
            String strCreditsSoFar;
            String strGPA;
            
            Student majoring = new Student();
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the file name: ");
            strFilename = scnr.next();
            
            if( !strFilename.equals("") ) {
                // Indicate that you are planning to opena file
                File fleStudent = new File(strFilename);
                // Prepare a Scanner that will "scan" the document
                Scanner opnStudentInfo = new Scanner(fleStudent);
    
                // Read each line in the file
                while( opnStudentInfo.hasNext() ) {
                    // Read each line and display its value
                    strStudentIdentificationNumber = opnStudentInfo.nextLine();
                    majoring.StudentIdentificationNumber =
                            Integer.parseInt(strStudentIdentificationNumber);
                    majoring.FirstName = opnStudentInfo.nextLine();
                    majoring.LastName = opnStudentInfo.nextLine();
                    strCreditsSoFar = opnStudentInfo.nextLine();
                    majoring.CreditsSoFar = Integer.parseInt(strCreditsSoFar);
                    strGPA = opnStudentInfo.nextLine();
                    majoring.GPA = Double.parseDouble(strGPA);
                }
                
                // De-allocate the memory that was used by the scanner
                opnStudentInfo.close();
            }
            
            return majoring;
        }
        
        public static void show(Student std) throws Exception {
            System.out.println("Student Record");
            System.out.println("Student ID: " + std.StudentIdentificationNumber);
            System.out.println("First Name: " + std.FirstName);
            System.out.println("Last Name: " + std.LastName);
            System.out.println("Number of credits so far: " + std.CreditsSoFar);
            System.out.println("Grade point average: " + std.GPA);
        }
        
        public static void main(String[] args) throws Exception {
            String mainAnswer = "Q", answer = "N";
            Scanner scnr = new Scanner(System.in);
            
            System.out.println("State University");
            System.out.println("What do you want to do?");
            System.out.println("R - Register a student");
            System.out.println("V - View a student information");
            System.out.println("Q - Exit or Quit");
            System.out.print("Your Answer? ");
            mainAnswer = scnr.next();
            
            if( (mainAnswer.equals("r")) || (mainAnswer.equals("R")) ) {
                Student std = register();
                
                System.out.print("Do you want to save this information (y/n)? ");
                answer = scnr.next();
                if( (answer.equals("y")) || (answer.equals("Y")) ) {
                    show(std);
                    save(std);
                }
            }
            else if( (mainAnswer.equals("v")) || (mainAnswer.equals("V")) ) {
                Student std = open();
                show(std);
            }
            else
                System.out.println("Good Bye!!!");
        }
    }
  2. Execute the application
  3. On the menu, indicate that you want to view a student record
  4. Enter one of the student file names and press Enter

File Management

Checking the Existence of a File

Besides writing to a file or reading from it, there are many other actions you may to perform on a file.

If you try opening a file that does not exist, you would receive an error:

Exception in thread "main" java.io.FileNotFoundException: Example1.xpl (The system 
cannot find the file specified)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.util.Scanner.<init>(Unknown Source)
        at Exercise.main(Exercise.java:9)

Therefore, before opening a file, you may want to check first whether it exists. To assist you with this, the File class is equipped with the exists() method. Here is an example of calling it:

import java.io.File;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to opena file
	File fleExample = new File("Example1.xpl");
        
        // Find out if the file exists already
        if( fleExample.exists() ) {
	    // Prepare a Scanner that will "scan" the document
            Scanner opnScanner = new Scanner(fleExample);
	    // Read each line in the file
            while( opnScanner.hasNext() ) {
		// Read each line and display its value
	    	System.out.println("First Name:    " + opnScanner.nextLine());
	    	System.out.println("Last Name:     " + opnScanner.nextLine());
	    	System.out.println("Hourly Salary: " + opnScanner.nextLine());
	    	System.out.println("Is Full Time?: " + opnScanner.nextLine());
	    }
	
	    // De-allocate the memory that was used by the scanner
            opnScanner.close();   
	}
        else // if( !fleExample.exists() )
            System.out.println("No file exists with that name");
             
    }
}

Deleting a File

To delete a file, you can call the delete() method of the File class.

Multidimensional Arrays

Fundamentals of Multidimensional Arrays

Introduction

The arrays we used so far were made of a uniform series, where all members consisted of a simple list, like a column of names on a piece of paper. Also, all items fit in one list. This type of array is referred to as one-dimensional.

In some cases, you may want to divide the list in delimited sections. For example, if you create a list of names, you may want part of the list to include family members and another part of the list to include friends. Instead of creating a second list, you can add a second dimension to the list. In other words, you would create a list of a list, or one list inside of another list, although the list is still made of items with common characteristics.

A multidimensional array is a series of arrays so that each array contains its own sub-array(s).

Practical LearningPractical Learning: Introducing Multidimensional Arrays

  1. Start NetBeans
  2. Create a new Java Application named DepartmentStore5
  3. Change the Main.java file as follows:
    package departmentstore5;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            long itemID = 0;
            double price = 0.00d;
            String description = "Unknown";
                
            System.out.println("Item Identification");
            System.out.println("Item Number: " + itemID);
            System.out.println("Description: " + description);
            System.out.printf("Unit Price:  %.2f\n", price);
        }
    }
  4. Execute the application to see the result. This would produce:
    Receipt
    Item Number: 0
    Description: Unknown
    Unit Price:  $0.00

Creating a Two-Dimensional Array

The most basic multidimensional array is made of two dimensions. This is referred to as two-dimensional.  To create a two-dimensional array, inside of one pair of square brackets, use two pairs (of square brackets). The formula you would use is:

DataType[][] VariableName;

Although the pairs of brackets are empty, they will contain some numbers. There are various ways you can initialize a two-dimensional array. If you are declaring the array variable but are not ready to initialize it, use the following formula:

DataType[][] VariableName = new DataType[Number1][Number2];

In Java, you can place the first square brackets on the right side of the name of the variable:

DataType VariableName[][] = new DataType[Number1][Number2];

In the square brackets on the right side of the = operator, enter an integer in each. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][4];
    }
}

In our declaration, the members variable contains two lists. Each of the two lists contains 4 elements. This means that the first list contains 4 elements and the second list contains 4 elements. Therefore, the whole list is made of 8 elements (2 * 4 = 8). Because the variable is declared as a String, each of the 8 items must be a string.

You can also create a two-dimensional array that takes more than two lists, such as 3, 4, 5 or more. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][8];
    }
}

This time, the variable is a 2-dimensional (2 lists) array where each list contains 8 components. This means that the whole array contains 2 * 8 = 16 components.

If you want to declare the array variable using the first formula where you do not know the sizes of the lists, you must use the data type of the array and you can omit the right square brackets. Here is an example:

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

Initializing a Two-Dimensional Array

There are various ways you can initialize a multidimensional array. You can initialize an array variable when declaring it. To do this, on the right side of the declaration, do not include the values in the square brackets:

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

Before the closing semi-colon, type an opening and a closing curly brackets. Inside of the brackets, include a pair of an opening and a closing curly brackets for each internal array. Then, inside of a pair of curly brackets, provide a list of the values of the internal array, just as you would do for a one-dimensional array. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] Members = new String[][] {
	    { "Celeste", "Mathurin", "Alex", "Germain" },   // First List
	    { "Jeremy", "Mathew", "Anselme", "Frederique" } // Second List
        };
    }
}

Practical Learning Practical Learning: Creating a Two-Dimensional Array

  1. To create and use a two-dimensional array, change the file as follows:
    package departmentstore5;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            long itemID = 0;
            double price = 0.00d;
            String description = "Unknown";
    
            // The first list contains women's items
            // The other contains non-women items
            long[][] itemNumbers = new long[][] {
                { 947783, 934687, 973947, 987598, 974937 },
                { 739579, 367583, 743937, 437657, 467945 } };
                
            String[][] itemNames = new String[][] {
                {
                    "Women Double-faced wool coat",
                    "Women Floral Silk Tank Blouse",
                    "Women Push Up Bra",
                    "Women Chiffon Blouse",
                    "Women Bow Belt Skirtsuit"
                },
                {
                    "Men Cotton Polo Shirt",
                    "Children Cable-knit Sweater  ",
                    "Children Bear Coverall Cotton",
    	        "Baby three-piece Set         ",
    	        "Girls Jeans with Heart Belt  "
                }
            };
    
            double[][] unitPrices = new double[][] {
                { 275.25D, 180.05D, 50.00D, 265.35D, 245.55D },
    	    {  45.55D,  25.65D, 28.25D,  48.55D,  19.95D }
            };
            
            System.out.println("Item Identification");
            System.out.println("Item Number: " + itemID);
            System.out.println("Description: " + description);
            System.out.printf("Unit Price:  %.2f\n", price);
        }
    }
  2. Save the file

Accessing the Members of a Two-Dimensional Array

To use the members of a two-dimensional array, you can access each item individually. For example, to initialize a two-dimensional array, you can access each member of the array and assign it a value. The external list is zero-based. In other words, the first list has an index of 0, the second list has an index of 1. Internally, each list is zero-based and behaves exactly like a one-dimensional array.

To access a member of the list, type the name of the variable followed by the square brackets. In the left brackets, type the index of the list. In the right square brackets, type the index of the component inside the internal list, the member whose access you need. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][4];

        members[0][0] = "Celeste";    // Member of the First List
        members[0][1] = "Mathurin";   // Member of the First List
        members[0][2] = "Alex";       // Member of the First List
        members[0][3] = "Germain";    // Member of the First List
        members[1][0] = "Jeremy";     // Member of the Second List
        members[1][1] = "Mathew";     // Member of the Second List
        members[1][2] = "Anselme";    // Member of the Second List
        members[1][3] = "Frederique"; // Member of the Second List
    }
}

You can use this same technique to retrieve the value of each member of the array. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][4];

        members[0][0] = "Celeste";    // Member of the First List
        members[0][1] = "Mathurin";   // Member of the First List
        members[0][2] = "Alex";       // Member of the First List
        members[0][3] = "Germain";    // Member of the First List
        members[1][0] = "Jeremy";     // Member of the Second List
        members[1][1] = "Mathew";     // Member of the Second List
        members[1][2] = "Anselme";    // Member of the Second List
        members[1][3] = "Frederique"; // Member of the Second List

        System.out.println(members[0][0]);
        System.out.println(members[0][1]);
        System.out.println(members[0][2]);
        System.out.println(members[0][3]);
        System.out.println(members[1][0]);
        System.out.println(members[1][1]);
        System.out.println(members[1][2]);
        System.out.println(members[1][3]);
    }
}

This would produce:

Celeste
Mathurin
Alex
Germain
Jeremy
Mathew
Anselme
Frederique

As we described it earlier, a two-dimensional array is a list of two arrays, or two arrays of arrays. In other words, the second arrays are nested in the first arrays. In the same way, if you want to access them using a loop, you can nest one for loop inside of a first for loop. The external loop accesses a member of the main array and the second loop accesses the internal list of the current array. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][4];

        members[0][0] = "Celeste";    // Member of the First List
        members[0][1] = "Mathurin";   // Member of the First List
        members[0][2] = "Alex";       // Member of the First List
        members[0][3] = "Germain";    // Member of the First List
        members[1][0] = "Jeremy";     // Member of the Second List
        members[1][1] = "Mathew";     // Member of the Second List
        members[1][2] = "Anselme";    // Member of the Second List
        members[1][3] = "Frederique"; // Member of the Second List

	for (int external = 0; external < 2; external++)
            for (int internal = 0; internal < 4; internal++)
                System.out.println(members[external][internal]);
    }
}

Practical LearningPractical Learning: Accessing the Members

  1. To retrieve the values of a two-dimensional array, change the file as follows:
    package departmentstore5;
    import java.io.*;
    import java.util.InputMismatchException;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            long itemID = 0;
            double price = 0.00d;
            boolean itemFound = false;
            String description = "Unknown";
            BufferedReader br =
                    new BufferedReader(new InputStreamReader(System.in));
    
            // The first list contains women's items
            // The other contains non-women items
            long[][] itemNumbers = new long[][] {
                { 947783, 934687, 973947, 987598, 974937 },
                { 739579, 367583, 743937, 437657, 467945 } };
                
            String[][] itemNames = new String[][] {
                {
                    "Women Double-faced wool coat",
                    "Women Floral Silk Tank Blouse",
                    "Women Push Up Bra",
                    "Women Chiffon Blouse",
                    "Women Bow Belt Skirtsuit"
                },
                {
                    "Men Cotton Polo Shirt",
                    "Children Cable-knit Sweater  ",
                    "Children Bear Coverall Cotton",
    	        "Baby three-piece Set         ",
    	        "Girls Jeans with Heart Belt  "
                }
            };
    
            double[][] unitPrices = new double[][] {
                { 275.25D, 180.05D, 50.00D, 265.35D, 245.55D },
    	    {  45.55D,  25.65D, 28.25D,  48.55D,  19.95D }
            };
    
            // Order Processing
            try {
                System.out.print("Enter Item Number: ");
                    itemID = Long.parseLong(br.readLine());
            }
            catch(InputMismatchException ime) {
                System.out.println("Invalid Number - The program will terminate");   
            }
    
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 5; j++) {
                    if (itemID == itemNumbers[i][j]) {
                        description = itemNames[i][j];
                        price = unitPrices[i][j];
                        itemFound = true;
                    }
                }
            }
            
            if( itemFound == true ) {
                System.out.println("Item Identification");
                System.out.println("Item Number: " + itemID);
                System.out.println("Description: " + description);
                System.out.printf("Unit Price:  %.2f\n", price);
            }
            else
                System.out.println("No item with that number was found.");
            
        }
    }
  2. Execute the application and test it. Here is an example:
    Enter Item Number: 367582
    No item with that number was found.
  3. Execute the application again and enter a different item number. Here is an example:
    Enter Item Number: 367583
    Item Identification
    Item Number: 367583
    Description: Children Cable-knit Sweater  
    Unit Price:  25.65

Multidimensional Arrays

Introduction

Beyond two dimensions, you can create an array variable that represents various lists, each list would contain various internal lists, and each internal list would contain its own components. This is referred to as a multidimensional array. One of the rules you must follow is that, as always, all members of the array must be of the same type.

Creating a Multidimensional Array

To create a multidimensional array, add as many pairs of square brackets you need. If you only want to declare the variable without indicating the actual number of lists, you can specify the data type followed by square brackets. Here is an example that represents a three-dimensional array that is not initialized:

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

If you know the types of members the array will use, you can use the assignment operator and specify the numbers of lists in the square brackets. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        double[][][] numbers = new double[2][3][5];
    }
}

In this example, we are creating 2 groups of items. Each of the two groups is made of three lists. Each list contains 5 numbers. As a result, the array contains 2 * 3 * 5 = 30 components. To better understand this, consider that the left square brackets represent a page in a book, the middle square brackets represent a table drawn on the page, and the right square brackets represent each item in the table.

Initializing a Multidimensional Array

As always, there are various ways you can initialize an array. To initialize a multidimensional array when creating it, you use a pair of curly brackets for each list. The most left pair of curly brackets represents the main array (a page in the book). After the left curly brackets, the second curly brackets represent an inside list (like a table in a page). The right square brackets represent the actual items in the array. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        double[][][] numbers = new double[][][]	{
	    {
		{  12.44, 525.38,  -6.28,  2448.32, 632.04 },
		{-378.05,  48.14, 634.18,   762.48,  83.02 },
		{  64.92,  -7.44,  86.74,  -534.60, 386.73 }
	    },
	    {
		{  48.02, 120.44,   38.62,  526.82, 1704.62 },
		{  56.85, 105.48,  363.31,  172.62,  128.48 },
		{  906.68, 47.12, -166.07, 4444.26,  408.62 }
	    }
	};
    }
}

Accessing the Members of a Multidimensional Array

To access a member of a multidimensional array, type the name of the array followed by the necessary square brackets. In the left square brackets, type the external index (the page of a book). In the second square brackets, type the index of the list. In the last square brackets, type the index of the item you want to access. After doing this, you can assign a value to the item. Here are examples:

public class Exercise {
    public static void main(String[] args) throws Exception {
        double[][][] numbers = new double[2][3][5];
	
	numbers[0][0][0] = 12.44;
	numbers[0][1][1] = 525.38;
	numbers[0][2][2] = -6.28;
	numbers[0][0][3] = 2448.32;
	numbers[0][1][4] = 632.04;
	numbers[0][2][0] = -378.05;
	numbers[0][0][1] = 48.14;
	numbers[0][1][2] = 634.18;
	numbers[0][2][3] = 762.48;
	numbers[0][0][4] = 83.02;
	numbers[0][1][0] = 64.92;
	numbers[0][2][1] = -7.44;
	numbers[0][0][2] = 86.74;
	numbers[0][1][3] = -534.60;
	numbers[0][2][4] = 386.73;
	numbers[1][0][0] = 48.02;
	numbers[1][1][1] = 120.44;
	numbers[1][2][2] = 38.62;
	numbers[1][0][3] = 526.82;
	numbers[1][1][4] = 1704.62;
	numbers[1][2][0] = 56.85;
	numbers[1][0][1] = 105.48;
	numbers[1][1][2] = 363.31;
	numbers[1][2][3] = 172.62;
	numbers[1][0][4] = 128.48;
	numbers[1][1][0] = 906.68;
	numbers[1][2][1] = 47.12;
	numbers[1][0][2] = -166.07;
	numbers[1][1][3] = 4444.26;
	numbers[1][2][4] = 408.62;
    }
}

This is the same approach you can use to access each member of the array to check or retrieve its value. Here are examples:

public class Exercise {
    public static void main(String[] args) throws Exception {
	double[][][] numbers = new double[][][]	{
	    {
		{  12.44, 525.38,  -6.28,  2448.32, 632.04 },
		{-378.05,  48.14, 634.18,   762.48,  83.02 },
		{  64.92,  -7.44,  86.74,  -534.60, 386.73 }
	    },
	    {
		{  48.02, 120.44,   38.62,  526.82, 1704.62 },
		{  56.85, 105.48,  363.31,  172.62,  128.48 },
		{  906.68, 47.12, -166.07, 4444.26,  408.62 }
	    }
	};

        System.out.println("numbers[0][0][0] = " + numbers[0][0][0]);
        System.out.println("numbers[0][0][1] = " + numbers[0][0][1]);
        System.out.println("numbers[0][0][2] = " + numbers[0][0][2]);
        System.out.println("numbers[0][0][3] = " + numbers[0][0][3]);
        System.out.println("numbers[0][0][4] = " + numbers[0][0][4]);

        System.out.println("\nnumbers[0][1][0] = " + numbers[0][1][0]);
        System.out.println("numbers[0][1][1] = " + numbers[0][1][1]);
        System.out.println("numbers[0][1][2] = " + numbers[0][1][2]);
        System.out.println("numbers[0][1][3] = " + numbers[0][1][3]);
        System.out.println("numbers[0][1][4] = " + numbers[0][1][4]);

        System.out.println("\nnumbers[0][2][0] = " + numbers[0][2][0]);
        System.out.println("numbers[0][2][1] = " + numbers[0][2][1]);
        System.out.println("numbers[0][2][2] = " + numbers[0][2][2]);
        System.out.println("numbers[0][2][3] = " + numbers[0][2][3]);
        System.out.println("numbers[0][2][4] = " + numbers[0][2][4]);

        System.out.println("\nnumbers[1][0][0] = " + numbers[1][0][0]);
        System.out.println("numbers[1][0][1] = " + numbers[1][0][1]);
        System.out.println("numbers[1][0][2] = " + numbers[1][0][2]);
        System.out.println("numbers[1][0][3] = " + numbers[1][0][3]);
        System.out.println("numbers[1][0][4] = " + numbers[1][0][4]);

        System.out.println("\nnumbers[1][1][0] = " + numbers[1][1][0]);
        System.out.println("numbers[1][1][1] = " + numbers[1][1][1]);
        System.out.println("numbers[1][1][2] = " + numbers[1][1][2]);
        System.out.println("numbers[1][1][3] = " + numbers[1][1][3]);
        System.out.println("numbers[1][1][4] = " + numbers[1][1][4]);

        System.out.println("\nnumbers[1][2][0] = " + numbers[1][2][0]);
        System.out.println("numbers[1][2][1] = " + numbers[1][2][1]);
        System.out.println("numbers[1][2][2] = " + numbers[1][2][2]);
        System.out.println("numbers[1][2][3] = " + numbers[1][2][3]);
        System.out.println("numbers[1][2][4] = " + numbers[1][2][4]);
    }
}

This would produce:

Number[0][0][0] = 12.44
Number[0][0][1] = 525.38
Number[0][0][2] = -6.28
Number[0][0][3] = 2448.32
Number[0][0][4] = 632.04

Number[0][1][0] = -378.05
Number[0][1][1] = 48.14
Number[0][1][2] = 634.18
Number[0][1][3] = 762.48
Number[0][1][4] = 83.02

Number[0][2][0] = 64.92
Number[0][2][1] = -7.44
Number[0][2][2] = 86.74
Number[0][2][3] = -534.6
Number[0][2][4] = 386.73

Number[1][0][0] = 48.02
Number[1][0][1] = 120.44
Number[1][0][2] = 38.62
Number[1][0][3] = 526.82
Number[1][0][4] = 1704.62

Number[1][1][0] = 56.85
Number[1][1][1] = 105.48
Number[1][1][2] = 363.31
Number[1][1][3] = 172.62
Number[1][1][4] = 128.48

Number[1][2][0] = 906.68
Number[1][2][1] = 47.12
Number[1][2][2] = -166.07
Number[1][2][3] = 4444.26
Number[1][2][4] = 408.62

Since the lists are nested, if you want to use loops to access the members of the array, you can nest the for loops to incrementally access the values. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	double[][][] numbers = new double[][][]	{
	    {
		{  12.44, 525.38,  -6.28,  2448.32, 632.04 },
		{-378.05,  48.14, 634.18,   762.48,  83.02 },
		{  64.92,  -7.44,  86.74,  -534.60, 386.73 }
	    },
	    {
		{  48.02, 120.44,   38.62,  526.82, 1704.62 },
		{  56.85, 105.48,  363.31,  172.62,  128.48 },
		{  906.68, 47.12, -166.07, 4444.26,  408.62 }
	    }
	};

	for(int page = 0; page < 2; page++)
            for(int table = 0; table < 3; table++)
                for(int value = 0; value < 5; value++)
        	    System.out.println("Number = " +
			numbers[page][table][value]);
    }
}

This would produce:

Number = 12.44
Number = 525.38
Number = -6.28
Number = 2448.32
Number = 632.04
Number = -378.05
Number = 48.14
Number = 634.18
Number = 762.48
Number = 83.02
Number = 64.92
Number = -7.44
Number = 86.74
Number = -534.6
Number = 386.73
Number = 48.02
Number = 120.44
Number = 38.62
Number = 526.82
Number = 1704.62
Number = 56.85
Number = 105.48
Number = 363.31
Number = 172.62
Number = 128.48
Number = 906.68
Number = 47.12
Number = -166.07
Number = 4444.26
Number = 408.62

Multidimensional Arrays and Classes

Introduction

Like an array of a primitive type, a multidimensional array can be made a field of a class. You can primarily declare it without initializing it. Here is an example:

public class TriangleInCoordinateSystem {
    private int[][] points;
}

This indicates a two-dimensional array field: the array will contain two lists but we don’t know (yet) how many members each array will contain. Therefore, if you want, when creating the array, you can specify its dimension by assigning it a second pair of square brackets using the new operator and the data type. Here is an example:

public class TriangleInCoordinateSystem {
    private int[][] points = new int[3][2];
}

You can also use a method of the class or a constructor to indicate the size of the array. Here is an example:

public class TriangleInCoordinateSystem {
    private int[][] points;

    public TriangleInCoordinateSystem() {
        points = new int[3][2];
    }
}

To initialize the array, you can access each member using the square brackets as we saw in the previous sections. Here is an example:

public class TriangleInCoordinateSystem {
    private int[][] Points;

    public TriangleInCoordinateSystem() {
        Points = new int[3][2];

        points[0][0] = -2; // A(x, )
        points[0][1] = -3; // A( , y)
        points[1][0] =  5; // B(x, )
        points[1][1] =  1; // B( , y)
        points[2][0] =  4; // C(x, )
        points[2][1] = -2; // C( , y)
    }
}

After initializing the array, you can use it as you see fit. For example, you can display its values to the user. Here is an example:

class TriangleInCoordinateSystem {
    private int[][] points;

    public TriangleInCoordinateSystem() {
        points = new int[3][2];

        points[0][0] = -2; // A(x, )
        points[0][1] = -3; // A( , y)
        points[1][0] =  5; // B(x, )
        points[1][1] =  1; // B( , y)
        points[2][0] =  4; // C(x, )
        points[2][1] = -2; // C( , y)
    }

    public void showPoints() {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", points[0][0], points[0][1]);
        System.out.printf("B(%d, %d)\n", points[1][0], points[1][1]);
        System.out.printf("C(%d, %d)", points[2][0], points[2][1]);
    }
}

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

        triangle.showPoints();
    }
}

This would produce:

Coordinates of the Triangle
A(-2, -3)
B(5, 1)
C(4, -2)

A Multidimensional Array as Argument

A multidimensional array can be passed as argument. When creating the method, in its parentheses, enter the data type followed by the necessary number of combinations of square brackets. Here is an example:

public class TriangleInCoordinateSystem {
    public void showPoints(int[][] Coords) {
    }
}

When defining the method, in its body, you can use the array as you see fit, such as displaying its values. Here is an example:

public class TriangleInCoordinateSystem {
    public void showPoints(int[][] pts) {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", pts[0][0], pts[0][1]);
        System.out.printf("B(%d, %d)\n", pts[1][0], pts[1][1]);
        System.out.printf("C(%d, %d)", pts[2][0], pts[2][1]);
    }
}

To call this type of method, pass only the name of the array. Here is an example:

class TriangleInCoordinateSystem {
    public TriangleInCoordinateSystem() {
    }

    public void showPoints(int[][] pts) {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", pts[0][0], pts[0][1]);
        System.out.printf("B(%d, %d)\n", pts[1][0], pts[1][1]);
        System.out.printf("C(%d, %d)", pts[2][0], pts[2][1]);
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
        int points[][] = new int[3][2];

        points[0][0] = -2; // A(x, )
        points[0][1] = -3; // A( , y)
        points[1][0] =  5; // B(x, )
        points[1][1] =  1; // B( , y)
        points[2][0] =  4; // C(x, )
        points[2][1] = -2; // C( , y)

	TriangleInCoordinateSystem triangle = new TriangleInCoordinateSystem();

        triangle.showPoints(points);
    }
}

As indicated with one-dimensional arrays, when passing an multi-dimensional array as argument, the array is treated as a reference. This makes it possible for the method to modify the array and return it changed. Here is an example:

class TriangleInCoordinateSystem {
    public void createPoints(int[][] coords) {
        coords[0][0] = -2; // A(x, )
        coords[0][1] = -3; // A( , y)
        coords[1][0] =  5; // B(x, )
        coords[1][1] =  1; // B( , y)
        coords[2][0] =  4; // C(x, )
        coords[2][1] = -2; // C( , y)
    }

    public void showPoints(int[][] pts) {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", pts[0][0], pts[0][1]);
        System.out.printf("B(%d, %d)\n", pts[1][0], pts[1][1]);
        System.out.printf("C(%d, %d)", pts[2][0], pts[2][1]);
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	int points[][] = new int[3][2];

	TriangleInCoordinateSystem triangle =
		new TriangleInCoordinateSystem();
	triangle.createPoints(points);
        triangle.showPoints(points);
    }
}

Returning a Multidimensional Array

You can return a multi-dimensional array from a method. When creating the method, before its name, specify the data type followed by the multidimensional combination of square brackets. Here is an example:

public class TriangleInCoordinateSystem {
    public int[][] CreateTriangle() {
    }
}

In the body of the method, you can do what you want but, before exiting it, you must return an array of the same type that was created. Here is an example:

class TriangleInCoordinateSystem {
    public int[][] CreateTriangle() {
	int[][] values = new int[3][2];
	return values;
    }
}

When calling the method, you can assign it to an array of the same type it returns. Here is an example:

class TriangleInCoordinateSystem {
    public int[][] createTriangle() {
	int[][] values = new int[3][2];
    
        values[0][0] = 6; // A(x, )
        values[0][1] = 1; // A( , y)
        values[1][0] = 2; // B(x, )
        values[1][1] = 3; // B( , y)
        values[2][0] = 1; // C(x, )
        values[2][1] = 4; // C( , y)

	return values;
    }

    public void showPoints(int[][] pts) {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", pts[0][0], pts[0][1]);
        System.out.printf("B(%d, %d)\n", pts[1][0], pts[1][1]);
        System.out.printf("C(%d, %d)", pts[2][0], pts[2][1]);
    }
}

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

        TriangleInCoordinateSystem triangle = new TriangleInCoordinateSystem();

        coordinates = triangle.createTriangle();
        triangle.showPoints(coordinates);
    }
}

This would produce:

Coordinates of the Triangle
A(6, 1)
B(2, 3)
C(1, 4)

A Multidimensional Array of Objects

A Variable of a Multidimensional Array of Objects

As done for primitive data types, you can create a multi-dimensional array where each component is of a class type. Of course, you can use an existing class or you must first create a class. Here is an example:

public class Point {
    private int xCoord;
    private int yCoord;

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

To create a multidimensional array of objects without initializing it, you can use the following formula:

ClassName[][] VariableName;

If you know the number of instances of the class that the array will use, you can use the following formula:

ClassName[][] VariableName = new ClassName[Number1][Number2];

Remember that you can position the square brackets after the name of the variable:

ClassName VariableName[][] = new ClassName[Number1][Number2];

The ClassName factor is the name of the class that will make up each component of the array. The other sections follow the same rules we reviewed for the primitive types. For example, you can create an array without allocating memory for it as follows:

class Point {
    private int xCoord;
    private int yCoord;

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

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

If you know the number of components that the array will contain, you can use the right pair of square brackets, in which case you can specify the name of the class and the square brackets. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[2][2];
    }
}

This declaration creates a two-dimensional array of two Point objects: The array contains two lists and each list contains two Points.

To initialize a multidimensional array of objects, you can access each array member using its index, allocate memory for it using the new operator. After allocating memory for the member, you can then access its fields or methods to initialize it. Here is an example:

class Point {
    private int xCoord;
    private int yCoord;

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[2][2];

        line[0][0] = new Point(); // First Point A
        line[0][0].setX(-3);      // A(x,  )
        line[0][0].setY(8);       // A( , y)

        line[0][1] = new Point(); // Second Point B
        line[0][1].setX(4);       // B(x,  )
        line[0][1].setY(-5);      // B( , y)
    }
}

You can also initialize the array when creating it. Before doing this, you would need a constructor of the class and the constructor must take the argument(s) that would be used to initialize each member of the array. To actually initialize the array, you would need a pair of external curly brackets for the main array. Inside of the external curly brackets, create a pair of curly brackets for each sub-dimension of the array. Inside the last curly brackets, use the new operator to access an instance of the class and call its constructor to specify the values of the instance of the class. Here is an example:

class Point {
    private int xCoord;
    private int yCoord;

    public Point(int x, int y) {
        xCoord = x;
        yCoord = y;
    }

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[][] {
	    {
		new Point(-3, 8),
		new Point(4, -5)
	    }
        };
    }
}

Accessing the Members of a Multidimensional Array of Objects

To access the members of a multidimensional array of objects, apply the square brackets to a particular member of the array and access the desired field or method of the class. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[][] {
	    {
		new Point(-3, 8),
		new Point(4, -5)
	    }
        };

	System.out.println("Line =-=");
        System.out.printf("From A(%d, %d) to B(%d, %d)",
                          line[0][0].getX(), line[0][0].getY(),
                          line[0][1].getX(), line[0][1].getY());
    }
}

This would produce:

Line =-=
From A(-3, 8) to B(4, -5)

You can also use a loop to access the members of the array. To do this, create a first forloop that stops at the first dimension of the array – 1. Then, inside of a first for loop, nest afor loop for each subsequent dimension. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[][] {
	    {
		new Point(-3, 8),
		new Point(4, -5)
	    }
        };

	System.out.println("The points of the line are:");
        for(int i = 0; i < 1; i++)
            for(int j = 0; j < 2; j++)
                System.out.printf("(%d, %d)\n",
                          line[i][j].getX(), line[i][j].getY());
    }
}

This would produce:

The points of the line are:
(-3, 8)
(4, -5)

To apply a for each operator, access only each member of the internal list. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[][] {
	    {
		new Point(-3, 8),
		new Point(4, -5)
	    }
        };

	System.out.println("The points of the line are:");
	for(Point pts : line[0])
            System.out.printf("(%d, %d)\n",
                          pts.getX(), pts.getY());
    }
}

Multidimensional Arrays of Objects and Classes

Introduction

As done for primitive types, a multidimensional array of objects can be made a field of a class. You can declare the array without specifying its size. Here is an example:

public class Triangle {
    public Point[][] vertices;
}

If you know the dimensions that the array will have, you can specify them using the new operator at the same time you are creating the field. Here is an example:

public class Triangle {
    public Point[][] vertices = new Point[3][2];
}

This creation signals a multidimensional array of Point objects. It will consist of three lists and each list will contain two Point objects

To initialize the array, access each member by its index to allocate memory for it. Once you get the member, you access each one of its fields or properties and initialize it with the desired value. Here is an example:

public class Triangle {
    public Point[][] Vertices = new Point[3][2];

    public Triangle() {
        vertices[0][0] = new Point(); // Point A(x, y)
        vertices[0][0].setX(-2);      // A(x,  )
        vertices[0][0].setY(-4);      // A( , y)
        vertices[1][0] = new Point(); // Point B(x, y)
        vertices[1][0].setX(3);       // B(x,  )
        vertices[1][0].setY(5);       // B( , y)
        vertices[2][0] = new Point(); // Point C(x, y)
        vertices[2][0].setX(6);       // C(x,  )
        vertices[2][0].setY(-2);      // C( , y)
    }
}

If the class is equipped with the right constructor, you can use it to initialize each member of the array.

Once the array is ready, you can access each members using its index and manipulate it. For example you can display its value(s) to the user. Here is an example:

class Point {
    private int xCoord;
    private int yCoord;

    public Point() {
        xCoord = 0;
        yCoord = 0;
    }
    public Point(int x, int y) {
        xCoord = x;
        yCoord = y;
    }

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

class Triangle {
    public Point[][] vertices = new Point[3][2];

    public Triangle() {
        vertices[0][0] = new Point(); // Point A(x, y)
        vertices[0][0].setX(-2);      // A(x,  )
        vertices[0][0].setY(-4);      // A( , y)
        vertices[1][0] = new Point(); // Point B(x, y)
        vertices[1][0].setX(3);       // B(x,  )
        vertices[1][0].setY(5);       // B( , y)
        vertices[2][0] = new Point(); // Point C(x, y)
        vertices[2][0].setX(6);       // C(x,  )
        vertices[2][0].setY(-2);      // C( , y)
    }

    public void identify() {
        System.out.print("Triangle Vertices: ");
        System.out.printf("A(%d, %d),  B(%d, %d), and C(%d, %d)",
                          vertices[0][0].getX(), vertices[0][0].getY(),
                          vertices[1][0].getX(), vertices[1][0].getY(),
                          vertices[2][0].getX(), vertices[2][0].getY());
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Triangle tri = new Triangle();
        tri.identify();
    }
}

This would produce:

Triangle Vertices: A(-2, -4),  B(3, 5), and C(6, -2)

Passing a Multidimensional Array of Objects

You can pass a multidimensional array of objects as arguments. To do this, in the parentheses of the method, enter the class name followed by the appropriate combination of square brackets. Here is an example:

public class Triangle {
    public void create(Point[][] Points) {
    }
}

In the body of the method, use the array as you we have done so far. You can access its members to get to its values. Here are examples:

class Point {
    private int xCoord;
    private int yCoord;

    public Point() {
        xCoord = 0;
        yCoord = 0;
    }
    public Point(int x, int y) {
        xCoord = x;
        yCoord = y;
    }

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

class Triangle {
    public void create(Point[][] points) {
        points[0][0] = new Point(); // Point A(x, y)
        points[0][0].setX(-2);      // A(x,  )
        points[0][0].setY(-4);      // A( , y)
        points[1][0] = new Point(); // Point B(x, y)
        points[1][0].setX(3);       // B(x,  )
        points[1][0].setY(5);       // B( , y)
        points[2][0] = new Point(); // Point C(x, y)
        points[2][0].setX(6);       // C(x,  )
        points[2][0].setY(-2);      // C( , y)
    }

    public void identify(Point[][] coords) {
        System.out.print("Triangle Vertices: ");
        System.out.printf("A(%d, %d),  B(%d, %d), and C(%d, %d)",
                          coords[0][0].getX(), coords[0][0].getY(),
                          coords[1][0].getX(), coords[1][0].getY(),
                          coords[2][0].getX(), coords[2][0].getY());
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Triangle tri = new Triangle();
	Point vertices[][] = new Point[3][2];

	tri.create(vertices);
        tri.identify(vertices);
    }
}

Remember that an array passed as argument is in fact passed by reference.

Returning a Multidimensional Array of Objects

A method can return a multidimensional array of objects. If you are creating the method, before its name, type the name of the class followed by the desired combination of square brackets. Here is an example:

public class Triangle {
    public Point[][] create() {
    }
}

After implementing the method, before exiting it, make sure it returns the type of array that it was indicated to produce. Here is an example:

class Point {
    private int xCoord;
    private int yCoord;

    public Point() {
        xCoord = 0;
        yCoord = 0;
    }
    public Point(int x, int y) {
        xCoord = x;
        yCoord = y;
    }

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

class Triangle {
    public Point[][] create() {
	Point[][] points = new Point[3][2];
        points[0][0] = new Point(); // Point A(x, y)
        points[0][0].setX(4);       // A(x,  )
        points[0][0].setY(8);       // A( , y)
        points[1][0] = new Point(); // Point B(x, y)
        points[1][0].setX(2);       // B(x,  )
        points[1][0].setY(-1);      // B( , y)
        points[2][0] = new Point(); // Point C(x, y)
        points[2][0].setX(3);       // C(x,  )
        points[2][0].setY(0);       // C( , y)

	return points;
    }

    public void identify(Point[][] coords) {
        System.out.print("Triangle Vertices: ");
        System.out.printf("A(%d, %d),  B(%d, %d), and C(%d, %d)",
                          coords[0][0].getX(), coords[0][0].getY(),
                          coords[1][0].getX(), coords[1][0].getY(),
                          coords[2][0].getX(), coords[2][0].getY());
    }
}

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

	Point vertices[][] = tri.create();

        tri.identify(vertices);
    }
}

This would produce:

Triangle Vertices: A(4, 8),  B(2, -1), and C(3, 0)

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

Introduction to Arrays

A Series of Similar Items

Introduction

Imagine you want to create a program that would use a series of numbers. In algebra, we represent such a series as follows: X1, X2, X3, X4, X5. You can also represent a list of names as follows:

Alex

Gaston

Hermine

Jerry

So far, to use a series of items, we were declaring a variable for each of them. If the list was made of numbers, we would declare variables for such numbers as follows:

public class Exercise {
    public static void main(String[] args) {
	double number1 = 12.44;
        double number2 = 525.38;
        double number3 = 6.28;
        double number4 = 2448.32;
        double number5 = 632.04;
    }
}

Instead of using individual variables that share the same characteristics, you can group them in an entity like a regular variable. This group is called an array. Therefore, an array is a series of items of the same kind. It could be a group of numbers, a group of cars, a group of words, etc but all items of the array must be of the same type.

Practical LearningPractical Learning: Introducing Arrays

  1. Start NetBeans
  2. Create a Java Application named VideoCollection1

Array Creation

Before creating an array, you must first decide about the type its items will be made of. This information allows the compiler to know how much space each item of the group will require. This is because each item of the group will occupy its own memory space, just like any of the variables we have used so far.

After deciding about the type of data of each item that makes up the series, you must use a common name to identify them. The name is simply the same type of name you would use for a variable as we have used so far. The name allows you and the compiler to identify the area in memory where the items are located.

Thirdly, you must specify the number of items that will constitute the group. For the compiler to be able to allocate an adequate amount of space for the items of the list, once it knows how much space each item will require, it needs to know the number of items so an appropriate and large enough amount of space can be reserved. The number of items of an array is included in square brackets, as in [5].

An array is considered a reference type. Therefore, an array requests its memory using the new operator. Based on this, to declare an array is, you can use the following formula:

DataType[] VariableName = new DataType[Number];

or:

DataType VariableName[] = new DataType[Number];

In these formulas, the DataType factor can be one of the types we have used so far (char, int, float, double, String, etc). It can also be the name of a class as we will learn. Like a normal variable, an array must have a name, represented in our formula asVariableName. The square brackets on both side of the assignment operator are used to let the compiler know that you are declaring an array instead of a regular variable. Thenew operator allows the compiler to reserve memory. The Number factor is used to specify the number of items of the list.

Based on the above formula, here is an example of an array variable:

public class Exercise {
    public static void main(String[] args) {
	double[] numbers = new double[5];
    }
}

As seen in our second formula, in the Java language (unlike many other languages, including C/C++ or C#), you can place the left square brackets either after the data type or after the name of the variable. Therefore, both of the following declarations are correct:

public class Exercise {
    public static void main(String[] args) {
	double[] firstNumbers = new double[5];
	double secondNumbers[] = new double[5];
    }
}

Practical LearningPractical Learning: Creating an Array

  1. To create arrays, change the Main.java file as follows:
    package videocollection1;
    
    public class Main {
    
        public static void main(String[] args) {
            long[]   shelfNumbers = new long[10];
            String[] titles = new String[10];
            String[] directors = new String[10];
            int[]    lengths = new int[10];
            String[] ratings = new String[10];
            double[] prices = new double[10];
        }
    }
  2. Save the file

The Array Class

To provide extensive support for arrays, the Java language is equipped with a class named Array, which is defined in the java.util package. Whenever you create an array, it automatically becomes an object of type Array. Consequently, any array you create inherits the fields and methods of the Array class and you can directly use them on your array variable.

Because there are so many members in the Array class, we will review each as its becomes necessary.

The Length of an Array

In most operations that involve an array, you will need to know the number of the components in the series. To provide this information, the Array class is equipped with a field named length, which is of type int.

Initializing an Array

Introduction

When creating an array, you can specify the number of items that make up its list. Each item of the series is referred to as a component of the array. Once the array has been created, each one of its components is initialized with a 0 value. Most, if not all, of the time, you will need to change the value of each component to a value of your choice. This is referred to as initializing the array.

An array is primarily a variable; it is simply meant to carry more than one value. Like every other variable, an array can be initialized. There are two main techniques you can use to initialize an array. If you have declared an array as done above, to initialize it, you can access each one of its members and assign it a desired but appropriate value.

In algebra, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A Java (like most C-based languages including C++ and C#) array is zero-based. This means that the first member of the array has an index of 0, the second has an index of 1, and so on. In algebra, the series would be represented as X0, X1, X2, X3, and X4.

In Java, the index of a member of an array is written in its own square brackets. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double[] numbers = new double[5];

        numbers[0] = 12.44;
        numbers[1] = 525.38;
        numbers[2] = 6.28;
        numbers[3] = 2448.32;
        numbers[4] = 632.04;
    }
}

Besides this technique, you can also initialize the array as a whole when declaring it. To do this, remove the dimension in the square brackets. Then, on the right side of the declaration, before the closing semi-colon, type the values of the array members between curly brackets and separated by a comma. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
    }
}

Although the second square brackets are empty, the compiler can figure out the number of items.

Practical LearningPractical Learning: Initializing Some Arrays

  1. To initialize the arrays, change the file as follows:
    package videocollection1;
    
    public class Main {
    
        public static void main(String[] args) {
            long[] shelfNumbers = new long[] {
                    2985, 8024, 5170, 1304, 9187,
                    1193, 3082, 8632, 4633, 9623
            };
            String[] titles = new String[] {
                    "The Distinguished Gentleman",
                    "A Perfect Murder", "Chalte Chalte",
                    "Ransom", "Not Another Teen Movie",
                    "Madhubaala", "Get Shorty",
                    "Sneakers", "Born Invincible", "Hush"
            };
            String[] directors = new String[] {
                    "Jonathan Lynn", "Andrew Davis", "Aziz Mirza",
                    "Ron Howard", "Joel Gallen", "Shivram Yadav",
                    "Barry Sonnenfeld", "Paul Alden Robinson",
                    "Unknown", "Jonathan Darby"
            };
            int[] lengths = new int[] {
                    112, 108, 145, 121, 100, 0, 105, 126,  90,  96
            };
            String[] ratings = new String[] {
                    "R", "R", "N/R", "R", "Unrated",
                    "N/R", "R", "PG-13", "N/R", "PG-13"
            };
            double[] prices = new double[] {
                    14.95D, 19.95D, 22.45D, 14.95D, 9.95D,
                    17.50D,  9.95D,  9.95D,  5.95D, 8.75D
            };
        }
    
    }
  2. Save the file

Other Techniques of Initializing an Array

We have initialized our arrays so far with values we specified directly in the curly brackets. If you have declared and initialized some variables of the same type, you can use them to initialize an array. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double Area = 97394.2204D;
        double Distance = 982.84D;
        double Level = 27D;
        double Quantity = 237957.704D;

        double[] measures = new double[] { Area, Distance, Level, Quantity };
    }
}

The values can also come from constant variables. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	final double PI = 3.141592653;
        double squreRootOf2 = 1.414D;
        double e = 2.718D;
        final double RADIUSOFEARTH = 6370; // km
        double ln2 = 0.6931;

        double[] measures = new double[] { PI, squreRootOf2, e,
                                           RADIUSOFEARTH, ln2 };
    }
}

The values can also come from calculations, whether the calculation is from an initialized variable or made locally in the curly brackets. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	final double DESNSITYOFWATER = 1000; // kg/m3 ;
        double massOfEarth = 5.98 * 10e24; // kg
        double earthMoonDistance = 2.39 * 10e5; // miles

        double measures[] = new double[] {
            DESNSITYOFWATER, 9.30 * 10.7, massOfEarth, earthMoonDistance
        };
    }
}

The rule to follow is that, at the time the array is accessed, the compiler must be able to know exactly the value of each member of the array, no guessing.

All of the arrays we have declared so far were using only numbers. The numbers we used were decimal constants. If the array is made of integers, you can use decimal, hexadecimal values, or a combination of both. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	long red = 0xFF0000;
        long someColor = 0x800000;

        long[] colors = new long[] { 2510, red, 818203, someColor, 0xF28AC };
    }
}

An array can have types of values of any of the data types we have used so far. The rule to follow is that all members of the array must be of the same type. For example, you can declare an array of Boolean values, as long as all values can be evaluated to true or false. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	boolean[] fullTimeStudents = new boolean[] { true, true, true, 
						     false, true, false };
    }
}

As stated already, each value of a Boolean array must be evaluated to true or false. This means that you can use variables or expressions as members of the array. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double house1Value = 460885.85D;
        double house2Value = 685770.00D;

        boolean comparisons[] = new boolean[] { 25 < 10,
                                                house1Value == house2Value,
                                                true };
    }
}

As we will see when studying arrays and classes, you can use this technique to create an array of dates, times, or date and time values.

Accessing the Members of an Array

Introduction

After initializing an array, which means after each of its members has been given a value, you can access a member of the array to get, to manipulate, or even to change, its value. To access a member of the array, you use the square brackets as we saw above. As done for normal variables, one of the reasons for accessing a member of an array would be to display its value, which can be done by passing it to System.out.print() or to System.out.println(). Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        System.out.print(numbers[3]);
    }
}

This would produce:

2448.32

In the same way, you can access 1, a few or all members of the array. Here are examples:

public class Exercise {
    public static void main(String[] args) {
	double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        System.out.println(numbers[3]);
        System.out.println(numbers[0]);
        System.out.println(numbers[2]);
        System.out.println(numbers[4]);
        System.out.println(numbers[1]);
    }
}

This would produce:

2448.32
12.44
6.28
632.04
525.38

When accessing a member to display its value, you can also use System.out.printf(). To do this, pass the appropriate % expression to the first part of the method, and access the right member in the second part, based on its index. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        System.out.printf("%f", numbers[1]);
    }
}

Practical LearningPractical Learning: Using the Members of an Array

  1. To show the values of a member of an array, change the Main.java file as follows:
    package videocollection1;
    
    public class Main {
        public static void main(String[] args) {
            long[] shelfNumbers = new long[] {
                    2985, 8024, 5170, 1304, 9187,
                    1193, 3082, 8632, 4633, 9623
            };
            
            . . . No Change
            
            System.out.println("===============================");
            System.out.println("Video Information");
            System.out.println("-------------------------------");
            System.out.println("Shelf #:  " + shelfNumbers[1]);
            System.out.println("Title:    " + titles[1]);
            System.out.println("Director: " + directors[1]);
            System.out.println("Length:   " + lengths[1] + " minutes");
            System.out.println("Rating:   " + ratings[1]);
            System.out.printf("Price:    %.2f\n", prices[1]);
            System.out.println("===============================");
        }
    }
  2. Execute the application and test it. Here is an example:
    ===============================
    Video Information
    -------------------------------
    Shelf #:  8024
    Title:    A Perfect Murder
    Director: Andrew Davis
    Length:   108 minutes
    Rating:   R
    Price:    19.95
    ===============================

For an Indexed Member of the Array

We saw how you can use the square brackets to access each member of the array one at a time. That technique allows you to access one, a few, or each member. If you plan to access all members of the array instead of just one or a few, you can use the for loop. The formula to follow is:

for(DataType Initializer; EndOfRange; Increment) Do What You Want;

In this formula, the for keyword, the parentheses, and the semi-colons are required. TheDataType factor is used to specify how you will count the members of the array.

The Initializer specifies how you would indicate the starting of the count. As seen in Lesson 8, this initialization could use an initialized int-based variable.

The EndOfRange specifies how you would stop counting. If you are using an array, it should combine a conditional operation (<, <=, >, >=, or !=) with the number of members of the array minus 1.

The Increment factor specifies how you would move from one index to the next.

Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        for (int i = 0; i < 5; i++)
            System.out.println(numbers[i]);
    }
}

This would produce:

12.44
525.38
6.28
2448.32
632.04

In the above code, we knew the number of components in the array. Sometimes, this information will not be obvious. We saw already that the Array class is equipped with a field named length. You can use it in the second part of a for loop. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        for (int i = 0; i < numbers.length; i++)
            System.out.println(numbers[i]);
    }
}

When using a for loop, you should pay attention to the number of items you use. If you use a number n less than the total number of members – 1, only the first n members of the array would be accessed. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        for (int i = 0; i < 3; i++)
            System.out.printf("Number: %f\n", numbers[i]);
    }
}

This would produce:

Number: 12.440000
Number: 525.380000
Number: 6.280000

On the other hand, if you use a number of items higher than the number of members minus one, the program would produce an error (we saw that the compiler would throw an exception).

Practical LearningPractical Learning: Using a for Loop

  1. To use a for loop, change the Main.java file as follows:
    package videocollection1;
    
    public class Main {
        public static void main(String[] args) {
            
            . . . No Change
            
            System.out.println("===============================");
            System.out.println("Video Information");
            for (int i = 0; i < 10; i++) {
                System.out.println("===============================");
                System.out.printf("Video %d\n", i + 1);
                System.out.println("-------------------------------");
                System.out.println("Shelf #:  " + shelfNumbers[1]);
                System.out.println("Title:    " + titles[1]);
                System.out.println("Director: " + directors[1]);
                System.out.println("Length:   " + lengths[1] + " minutes");
                System.out.println("Rating:   " + ratings[1]);
                System.out.printf("Price:    %.2f\n", prices[1]);
            }
            System.out.println("===============================");
        }
    }
  2. Execute the application to see the result:
    ===============================
    Videos Information
    ===============================
    Video 1
    -------------------------------
    Shelf #:  2985
    Title:    The Distinguished Gentleman
    Director: Jonathan Lynn
    Length:   112 minutes
    Rating:   R
    Price:    14.95
    ===============================
    Video 2
    -------------------------------
    Shelf #:  8024
    Title:    A Perfect Murder
    Director: Andrew Davis
    Length:   108 minutes
    Rating:   R
    Price:    19.95
    ===============================
    Video 3
    -------------------------------
    Shelf #:  5170
    Title:    Chalte Chalte
    Director: Aziz Mirza
    Length:   145 minutes
    Rating:   N/R
    Price:    22.45
    ===============================
    Video 4
    -------------------------------
    Shelf #:  1304
    Title:    Ransom
    Director: Ron Howard
    Length:   121 minutes
    Rating:   R
    Price:    14.95
    ===============================
    Video 5
    -------------------------------
    Shelf #:  9187
    Title:    Not Another Teen Movie
    Director: Joel Gallen
    Length:   100 minutes
    Rating:   Unrated
    Price:    9.95
    ===============================
    Video 6
    -------------------------------
    Shelf #:  1193
    Title:    Madhubaala
    Director: Shivram Yadav
    Length:   0 minutes
    Rating:   N/R
    Price:    17.5
    ===============================
    Video 7
    -------------------------------
    Shelf #:  3082
    Title:    Get Shorty
    Director: Barry Sonnenfeld
    Length:   105 minutes
    Rating:   R
    Price:    9.95
    ===============================
    Video 8
    -------------------------------
    Shelf #:  8632
    Title:    Sneakers
    Director: Paul Alden Robinson
    Length:   126 minutes
    Rating:   PG-13
    Price:    9.95
    ===============================
    Video 9
    -------------------------------
    Shelf #:  4633
    Title:    Born Invincible
    Director: Unknown
    Length:   90 minutes
    Rating:   N/R
    Price:    5.95
    ===============================
    Video 10
    -------------------------------
    Shelf #:  9623
    Title:    Hush
    Director: Jonathan Darby
    Length:   96 minutes
    Rating:   PG-13
    Price:    8.75
    ===============================

For Each Member in the Array

In a for loop, you should know the number of members of the array. If you do not, the Java language allows you to let the compiler use its internal mechanism to get this count and use it to know where to stop counting. To assist you with this, you can use another version of the forloop. The formula to follow is:

for (ArrayType Identifier: ArrayName) Use the Identifier 

The for keyword, the parentheses, and the colon are required.

The first factor of this syntax, ArrayType is the same data type as the array (it can also be the name of a class as we will learn in when studying collections).

The Identifier factor is a name of the variable you will use. This name is used to represent each component of the array.

After the closing parenthesis, use the Identifier as you see fit. Like a for loop that accesses all members of the array, this other version is used to access each array member, one at a time. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        for(double number: numbers)
            System.out.printf("Number: %f\n", number);
    }
}

This would produce:

Number: 12.440000
Number: 525.380000
Number: 6.280000
Number: 2448.320000
Number: 632.040000

Practical LearningPractical Learning: Getting Each Component of an Array

  1. Change the file as follows:
    package videocollection1;
    
    public class Main {
        public static void main(String[] args) {
            
            . . . No Change
            
            System.out.println("Video Collection");
            for(String title : titles)
                System.out.println(title);
        }
    }
    
  2. Execute the application to see the result
    Video Collection
    The Distinguished Gentleman
    A Perfect Murder
    Chalte Chalte
    Ransom
    Not Another Teen Movie
    Madhubaala
    Get Shorty
    Sneakers
    Born Invincible
    Hush

Selecting a Value From an Array

Introduction

Because an array is a list of values, it can include items that are not useful in all scenarios. For example, having an array made of too many values, at one time you may want to isolate only the first n members of the array, or the last m members of the array, or a range of members from an index i to an index j. Another operation you may be interested to perform is to find out if this or that value exists in the array. One more interesting operation would be to find out what members or how many members of the array respond to this or that criterion. All these operations are useful and possible with different techniques.

Using a for Loop

Consider the following program:

public class Exercise {
    public static void main(String[] args) {
	short[] numbers = new short[] {
		102, 44, 525, 38, 6,
		28, 24481, 327, 632, 104 };

        for (int i = 0; i < numbers.length; i++)
            System.out.println("Number: " + numbers[i]);
    }
}

This would produce:

Number: 102
Number: 44
Number: 525
Number: 38
Number: 6
Number: 28
Number: 24481
Number: 327
Number: 632
Number: 104

Imagine you want to access only the first n members of the array. To do this, you can use an ifconditional statement nested in a for loop. Here is an example that produces the first 4 values of the array:

public class Exercise {
    public static void main(String[] args) {
	short[] numbers = new short[] {
		102, 44, 525, 38, 6,
		28, 24481, 327, 632, 104 };

        for (int i = 0; i < numbers.length; i++)
            if (i < 4)
                System.out.println("Number: " + numbers[i]);
    }
}

This would produce:

Number: 102
Number: 44
Number: 525
Number: 38

You can use the same technique to get the last m members of the array. You can also use a similar technique to get one or a few values inside of the array, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array:

public class Exercise {
    public static void main(String[] args) {
	short[] numbers = new short[] {
		102, 44, 525, 38, 6,
		28, 24481, 327, 632, 104 };

        for (int i = 0; i < numbers.length; i++)
            if (numbers[i] % 5 == 0)
                System.out.println("Number: " + numbers[i]);
    }
}

This would produce:

Number: 525

Practical LearningPractical Learning: Checking a Value From an Array

  1. To check a value from an array, change the file as follows:
    package videocollection1;
    import java.io.*;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            BufferedReader br =
                    new BufferedReader(new InputStreamReader(System.in));
            long[] shelfNumbers = new long[] {
                    2985, 8024, 5170, 1304, 9187,
                    1193, 3082, 8632, 4633, 9623
            };
            String[] titles = new String[] {
                    "The Distinguished Gentleman",
                    "A Perfect Murder", "Chalte Chalte",
                    "Ransom", "Not Another Teen Movie",
                    "Madhubaala", "Get Shorty",
                    "Sneakers", "Born Invincible", "Hush"
            };
            String[] directors = new String[] {
                    "Jonathan Lynn", "Andrew Davis", "Aziz Mirza",
                    "Ron Howard", "Joel Gallen", "Shivram Yadav",
                    "Barry Sonnenfeld", "Paul Alden Robinson",
                    "Unknown", "Jonathan Darby"
            };
            int[] lengths = new int[] {
                    112, 108, 145, 121, 100, 0, 105, 126,  90,  96
            };
            String[] ratings = new String[] {
                    "R", "R", "N/R", "R", "Unrated",
                    "N/R", "R", "PG-13", "N/R", "PG-13"
            };
            double[] prices = new double[] {
                    14.95D, 19.95D, 22.45D, 14.95D, 9.95D,
                    17.50D,  9.95D,  9.95D,  5.95D, 8.75D
            };
            
            System.out.println("===============================");
            System.out.println("Video Collection");
            System.out.print("Shelf Numbers: ");
            for(long code : shelfNumbers)
                    System.out.print(code + " ");
            System.out.println("\n===============================");            
    
            long shelfNumber = 0;
    
            System.out.print("Enter the shelf number of the " +
                             "video you want to check: ");
            shelfNumber = Long.parseLong(br.readLine());
            System.out.println();            
            
            for(int i = 0; i < 10; i++) {
                if (shelfNumbers[i] == shelfNumber) {
                    System.out.println("===============================");
                    System.out.println("Video Information");
                    System.out.println("-------------------------------");
                    System.out.println("Shelf #:  " + shelfNumbers[i]);
                    System.out.println("Title:    " + titles[i]);
                    System.out.println("Director: " + directors[i]);
                    System.out.println("Length:   " + lengths[i] + " minutes");
                    System.out.println("Rating:   " + ratings[i]);
                    System.out.printf("Price:    %.2f\n", prices[i]);
                }
            }
            System.out.println("===============================");
        }
    }
  2. Execute the application to test it
  3. When prompted, enter a shelf number and press Enter. Here is an example:
    ===============================
    Video Collection
    Shelf Numbers: 2985 8024 5170 1304 9187 1193 3082 8632 4633 9623 
    ===============================
    Enter the shelf number of the video you want to check: 5170
    
    ===============================
    Video Information
    -------------------------------
    Shelf #:  5170
    Title:    Chalte Chalte
    Director: Aziz Mirza
    Length:   145 minutes
    Rating:   N/R
    Price:    22.45
    ===============================

Date and Time Values in Java Applications

Introduction

A date is a measure of non-spatial units that have elapsed in a set period. To perform this measure, a certain point is set and called midnight. From that point, a number of units are counted until the next corresponding point is reached. Because the light in daily life changes from one midnight unit to the next midnight unit, the sub-point when the light shows up, or starts, is called sunrise.

The sub-point when the light diminishes or starts disappearing is called sunset. The midpoint between the sunrise and the sunset is called noon. The first part, from midnight to noon is referred to as AM in US English. The other part is referred to as PM in US English.

The group of units between two midnight points is called a day. The days are counted from 0, 1, and up. A group of seven consecutive days is called a week. The weeks are counted from 1 and up. To make it easy to identify a day, the days of a week are named in US English as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. These are referred to as long names. The corresponding short names in US English are Mon, Tue, Wed, Thu, Fri, Sat, and Sun. The day considered as the first of the week depends on the language and/or some other considerations. For example, in US English, Sunday is usually considered the first day of the week.

Most of the time, a group of four weeks is called a month. The months are counted from 1 and up. To make it easy to identify a month, each holds a long name. In US English, they are January, February, March, April, May, June, July, August, September, October, November, and December. Their short names in US English are Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. Except for the month of February that depends on a factor named Leap Year, the maximum days of each month are January=31, March=31, April=30, May=31, June=30, July=31, August=31, September=30, October=31, November=30, and December=31.

A group of three months is called a trimester. A group of four months is called a quarter. A group of six months is called a semester. A group of twelve months can be called a year. The years are counted from 1 and up (some compilers or applications specify when the years start; for example, some applications start their count at 1901 and cannot process years below that number; some other applications would not process a year beyond a certain year).

In a regular year, the months are counted from 1 to 12. The technique or expression used to identify a particular day during a year is called a date. The days are counted from 1 to 365 or 366 (depending on a factor called a leap year). A date can be the combination of a day, its month, and the year. There are other aspects that can be taken into consideration.

A unit of measure in a day is called a second. The seconds are counted from 0 to 59 or from 0, 1, 2, and so on. In some applications, when precision is particularly important, a second is considered a group of 1000 portions called milliseconds. The milliseconds are counted from 0 to 999.

A group of 60 seconds is called a minute. A group of 60 minutes is called an hour. A group of 24 hours is called a day. The technique or expression used to identify a particular unit of measure during a day is called the time. It can be the combination of the hour, the minute, and the second. Some other aspects may be taken into consideration.

Date Time Value Creation

To represent the dates, computers, applications, and compilers are configured with specific techniques and rules. To support date and time values, the java.utilpackage is equipped with a class named Date. To assist you with initializing the variable, the Date class is equipped with various constructors.

The default constructor allows you to create a date or a time object without specifying its details. This would be done as follows:

import java.util.Date;

public class Exercise {
    public static void main(String[] args) {
	Date tm = new Date();
    }
}

After declaring a Date variable and initializing it, it holds all necessary pieces of information about its date and its time values.

The Current Date and Time

The default constructor of the Date class initializes the Date variable with today’s date and time (at the time the variable was declared). This is illustrated in the following program:

import java.util.Date;

public class Exercise {
    public static void main(String[] args) {
	Date tm = new Date();

        System.out.println("Default Date and Time: " + tm);
    }
}

Based on the day and time this lesson was written, it produced:

Default Date and Time: Tue Jan 06 11:12:38 EST 2009

Random Numbers

Mathematics in Java

Introduction

Imagine you have a series of numbers, such these: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, and 20. Imagine you want to select one of these numbers, any of them. A number is referred to as random if it has been selected from a pool without a specific pattern to follow. For example, if you decide to select the value 17 from this list, if there was an exact reason that number was selected, then it is not considered random. In reality, it is difficult for a number to qualify as random. For this reason, most random numbers are referred to as pseudo-random.

Getting a Random Number

To support the ability to create or choose a random number, the java.util package contains a class named Random. To start, you can declare a variable of this class, using one of its two constructors. Here is an example that uses the default constructor:

import java.util.Random;

public class Exercise {
    public static void main(String[] args) {
	Random rndNumber = new Random();
    }
}

After declaring the variable, you can start getting numbers from it. The Random class allows you to get a Boolean value, a normal integer, a long integer, or a decimal value. To assist with this, the Random class provides the following methods:

Method
Produces

boolean nextBoolean();

A true or false value

int nextInt()

An integral value between Integer.MIN_VALUE andInteger.MAX_VALUE

long nextLong()

A long integral value between Long.MIN_VALUE andLong.MAX_VALUE

float nextFloat()

A decimal number between 0.0 (included) and 1.0 (excluded)

double nextDouble()

A decimal number between 0.0 (included) and 1.0 (excluded)

Here is an example of calling one of these methods:

import java.util.Random;

public class Exercise {
    public static void main(String[] args) {
	Random rndNumbers = new Random();
        int    rndNumber  = rndNumbers.nextInt();

        System.out.println("Number: " + rndNumber);
    }
}

Here is an example of running the program:

Number: 1369872590

In the same way, you can call the method repeatedly to get random numbers. Here is an example:

import java.util.Random;

public class Exercise {
    public static void main(String[] args) {
	Random rndNumbers = new Random();
        int rndNumber = 0;

        for (int nbr = 1; nbr < 9; nbr++) {
            rndNumber = rndNumbers.nextInt();
            System.out.println("Number: " + rndNumber);
        }
    }
}

Here is an example of running the program:

Number: 1783601039
Number: -646235293
Number: -57529965
Number: 983241665
Number: 1794072434
Number: 1797572448
Number: 1057090973
Number: -634503464

The Seed of a Random Number

Consider the following program:

import java.util.Random;

public class Exercise {
    public static void main(String[] args) {
	Random rndNumbers = new Random();
        int rndNumber = rndNumbers.nextInt();

        System.out.println("Number: " + rndNumber);
    }
}

Here is an example of running the program:

Number: 573991745

Here is another example of running the same program:

Number: 334223329

Notice that the numbers generated are different. When creating a program that repeatedly gets a series of random numbers, you may (or may not) want theRandom class to generate the same number over and over again. A seed is a constant value that controls whether a random generation would produce the same result every time it occurs. For example, using a seed, you can impose it upon theRandom class to generate the same number every time the nextInt() method is called. To support the ability to use a seed, the Random class is equipped with a second constructor whose syntax is:

public Random(long Seed);

Based on this, to specify a seed, when declaring a Random variable, pass a constant integer to the constructor. Here is an example:

import java.util.Random;

public class Exercise {
    public static void main(String[] args) {
	Random rndNumbers = new Random(20);
        int rndNumber = rndNumbers.nextInt();

        System.out.println("Number: " + rndNumber);
    }
}

Here is one example of running the program:

Number: 375271809

Here is another example of running the same program:

Number: 375271809

Notice that the numbers are the same. Consider this program also:

import java.util.Random;

public class Exercise {
    public static void main(String[] args) {
	Random rndNumbers = new Random(20);
        int rndNumber = 0;

        for (int nbr = 1; nbr < 5; nbr++) {
            rndNumber = rndNumbers.nextInt();
            System.out.println("Number: " + rndNumber);
        }
    }
}

Here is one example of running the program:

Number: 375271809
Number: 1472524622
Number: 1605850688
Number: 1776011503

Here is another example of running the same program:

Number: 375271809
Number: 1472524622
Number: 1605850688
Number: 1776011503

Notice that the sequences are the same. In both cases, this indicates that, if you specify a seed, the Random class would generate the same number or the same sequence of numbers.

Besides the second constructor, to specify the seed, you can call thesetSeed() method. Its syntax is:

void setSeed(long seed);

This method takes one argument as the seed. Here is an example of calling it:

import java.util.Random;

public class Exercise {
    public static void main(String[] args) {
	Random rndNumbers = new Random();

	rndNumbers.setSeed(20);
        int rndNumber = rndNumbers.nextInt();

        System.out.println("Number: " + rndNumber);
    }
}

Generating Random Numbers in a Range of Numbers

So far, we have been using any number that would fit an integer. In some assignments, you may want to restrict the range of numbers that can be extracted. The Random class can assist with this. Using the Random class, you can generate random positive numbers from 0 (included) to a maximum (excluded) of your choice. To support this, the Random class is equipped with another version of the nextInt() method whose syntax is:

public int nextInt(int maxValue);

The argument to pass to the method determines the highest integer that can be generated by the nextInt() method. The method returns an integer. Here is an example that generates random numbers from 0 to 20:

import java.util.Random;

public class Exercise {
    public static void main(String[] args) {
	Random rndNumbers = new Random();
        int rndNumber = 0;


        for (int nbr = 1; nbr < 9; nbr++) {
            rndNumber = rndNumbers.nextInt(20);
            System.out.println("Number: " + rndNumber);
        }
    }
}

Here is an example of running the program:

Number: 1
Number: 7
Number: 1
Number: 16
Number: 14
Number: 19
Number: 3
Number: 1

The above version of the Next() method generates numbers starting at 0.

The Math.Random Method

Besides the Random class, the Math class is equipped with a method that can be used to generate random numbers. The syntax of this method is:

static double random();

When called, this method produces a randomly selected decimal number between 0.00 (included) and 1.00 (excluded).