Using pre-written code
Header files don't exist in Java and the #include directive of C++ is not supported
The Java compiler makes it easy for programmers to use "packages" of existing code. Most packages contain dozens of related classes and interfaces with each having a number of useful methods. Among the most frequently used packages are:
Package
Contents
java.applet
Supports Java applets (small programs that may be embedded inside other applications - such as Web pages)
java.awt
The "abstract windows toolkit" supports graphical, Windows programming
java.lang
Supports Java language extensions and mathematical tools
java.text
Supports text formatting and manipulation
java.util
A set of general purpose utility classes
import java.util.*;
Notes:
- Code import statements at the beginning of the Java source file for all packages except java.lang. Its contents are automatically available.
- Don't forget the semicolon. This is a common mistake of programmers moving from C++ to Java.
- Optionally, only a selected class might be specified, such as
import java.util.stack;
which has features to help manage a first-in-first-out stack.
- Without an import statement pre-written code is still accessible, but each class reference would need to be prefaced by the package name. For example,
java.util.stack x = new java.util.stack();
Use the help facility to learn about Java packages, classes, interfaces, and their features. Of particular interest is the Math class in the java.lang package.
Watch for compiler warnings when using certain packaged code. In particular, a method may be "deprecated". Such methods have been marked as outdated and subject to removal. They should be avoided.
Arrays
double[] dailySales = new double[366];
Notes:
- Java allows the square brackets to be coded after the array's data type or after its identifier (as in C++). While you could re-code the above as
double dailySales[] = new double[366];
it will identify you as a C++ programmer who is new to Java.
- The number inside the second set of square brackets specifies how many elements the array will have. Rather than a literal, the identifier of an integer variable or constant, or an expression evaluating to an integer could be coded.
- Two separate statements could have been used to declare the array and obtain space for its elements, such as
double[] dailySales; dailySales = new double[366];
The first statement declares the array reference. The second statement allocates memory for all the array elements.
Unless otherwise specified, array elements are automatically initialized based upon their type. Numeric elements are set to 0, boolean elements are set to false, and character elements are set to binary zeroes.
Array elements can be initialized to specific values by coding a value list, such as
char[] transCode = {'A', 'U', 'D'};
When a value list is coded, the number of array elements is determined by the number of values in the list and the new operator is not coded.
While Java uses subscripts to access individual array elements in exactly the same way as C++, Java lets a program recover from an invalid subscript at run time by catching an ArrayIndexOutOfBoundsException. Exception handling will be covered later.
Knowing how many elements an array contains is easy in Java. Each array has a public int member named length that represents the number of elements. For example, the following class method would calculate the sum of all elements in an array of double values
public static double sumAll(double[] theArray) { double total = 0; for (int i = 0; i < theArray.length; i++) { total += theArray[i]; } return total; }
Strings
Unlike C++, Java stores strings as objects and not simply arrays of characters.
The Java String class simplifies the processing of string data (such as names, addresses, part descriptions, etc.). It differs from the String class of C++ and does not support the ANSI string functions found in C++.
Because the String class is in the java.lang package, no import statement is needed.
In Java, a String class object is immutable. Once created, it can never be changed.
The identifier of a Java String class object is an object reference. It points to the object in memory. For example, the following statement creates a String class object:
String jobTitle = "Clerk";
Notes:
- Alternatively, the object could have been constructed as follows:
String jobTitle = new String("Clerk");
- jobTitle is the object reference. It holds the address of where the String object with the value of "Clerk" resides in memory.
jobTitle
memory address
->
"Clerk"
- The reference can be reassigned and made to point at a different String class object. For example,
jobTitle = "Systems Analyst";
reassigns jobTitle to point at an object with the value "Systems Analyst". The object with the value "Clerk" remains in memory but is inaccessible.
jobTitle
memory address
->
"Systems Analyst"
"Clerk"
Inaccessible objects don't remain in memory forever. The Java "garbage collection" facility automatically disposes of objects that can no longer be referenced.
A common programming mistake involves the way in which strings are tested for equality. Consider the following code:
String x = "abc";
String y = new String("abc");
if (x == y) {
System.out.println("The strings are equal");
}
else {
System.out.println("The strings are different");
}Testing this code will result in the message that says the strings are different. This is caused by the use of the == operator. The code has tested contents of the two object references and NOT the values of the two objects.
To correctly compare two strings, replace the if statement with the following:
if (x.equals(y))
The equals() method tests the contents of two objects and NOT where they are located in memory.
The String class contains many other useful methods for working with strings. Refer to the help facility of your Java development environment for complete information.