Chapter 5: Using Classes in Java Programming
Now that we've seen how simple creating objects is in Java, it won't surprise you to discover that everything in Java is accomplished using classes. There are no library functions or independent subroutines in Java: only objects of various types and their methods. While this may take a slight attitude readjustment, you'll quickly see that the consistency this approach brings to Java makes it a very easy language to learn and use.
Like VB, strings in Java are one of the most commonly used objects and contain a fairly rich set of methods for manipulating character strings. Strings are not arrays in the sense that they are in C or VB, but you can manipulate groups of characters in an analogous manner. Remember that Strings contain 16-bit Unicode characters, so that the can represent a wide variety of fonts and languages.
The fact that an object may have any number of constructors,
each with different arguments is another example of polymorphism.
The most common string constructor is
String s = new String("abc");
but you can also create a string from an array of
characters from some file or network socket:
String(char[]) //from array of char //from specified part of array of char String(char[], int offset, int count) //from array, setting upper byte String(char[], int hibyte, int offset, int count)
The third constructor above is used to assure that the upper byte of each 16-bit character is set to a known value, usually zero. This function is very important in Windows 95, where Java 1.0 otherwise sets this upper byte to an indeterminate value, making comparisons with other strings impossible.
There are a wide variety of methods in the String
class. Some of the most common are:
length() equals(String) startsWith(String) endsWith(String) toUpperCase() toLowerCase() indexOf(String) subString(int begin) subString(int begin, int end)
To reiterate, these are methods that operate on a String object, not functions to be called with a string as argument. Thus, to obtain the length of a string, you might perform the following steps:
//create an 8-character string String abc = new String("alphabet"); int len = abc.length(); //len now contains 8
You can look over the plethora of other string methods in the String documentation provided with the SDK.
The +-sign in Java is said to be "overloaded" with respect to strings. Thus, you can combine strings much as you can in VB and Pascal:
String h = new String("Holiday"); String fs = new String("for Strings"); String title = h+ " " + fs; //prints "Holiday for Strings" System.out.println(title);
You can also use the +-operator to combine basic
numeric types with strings. They are automatically converted to
strings:
int count = 24; System.out.println("Found " + count + " blackbirds"); // prints out "Found 24 blackbirds"
Note that there are no leading or trailing spaces
in numbers produced in this fashion and you must be sure to include
them in your code.
You can convert any simple numeric type (int, float, double, etc.) to a string in one of two ways:
The simplest way is to convert using the String
class's valueOf() method.
int length = 120; String strLength = new String().valueOf(length); //returns a string "120"
There is a version of this method for each of the basic types: in other words this method shows polymorphism.
You can accomplish the same thing using the toString() methods of the Integer, Float and Double classes, which are object classes wrapped around the base numeric types:
int length = 120; String strLength = new Integer(length).toString();
To convert a String to a number, you can use the
intValue() , floatValue() and related versions
of the Integer and Float classes:
String strLength = new String("120"); int length = new Integer(strLength).intValue();
The String class is designed to be immutable: once you have created a string you cannot change its contents. The StringBuffer class is provided so you can change indivdual characters of a String and then put the changed result back into a string.
You can create an instance of the StringBuffer class from a string:
String alph = new String("abcde"); StringBuffer buf = new StringBuffer(alph);
Then you can examine or change any character using the following methods:
public char charAt(int n); //get char at posn n public void setCharAt(int n, char ch); //set char public StringBuffer insert(int n, char c);
as well as with a host of other useful methods listed in the documentation. When you have changed the characters in the string buffer, you can regenerate the string with the toString method.
alph = buf.toString();
Arrays are a built-in class whose syntax is part
of the language, much as Strings are. Arrays can be singly or
multiply dimensioned and may consist of any base numeric type
or of any object. You declare an array object by
float x[] = new float[100]; //dimension array
and you can access it by enclosing the index in brackets.
Note that array indices always begin at 0 and end at one less
than the array dimension:
for (i=0; i<100; i++) x[i] = i;
When you declare a new array, its elements are initialized
to 0 if it is numeric or to null if it is an array of objects.
You can also declare specific contents for an array:
int a[] = new int[5]; a[] = {1, 3, 5, 7, 9};
You can also declare arrays of more than one dimension
by including several dimensions in successive brackets:
float x[][] = new float[12][10];
int z[][][] = new int[3][2][3];
Because Java actually handles these multidimensional
arrays as arrays of objects, each with their own dimensions,
you do not have to specify all of the dimensions in the initial
declaration. The leftmost dimensions must be specified but dimensions
to the right may be omitted and defined later:
float abc[][] = new float[100][];
Here, abc is actually a single-dimensional array of float[], where these dimensions are not yet defined.
Once we begin allocating large amounts of memory in any program, we are naturally concerned about how that memory can be released when we are done with it. In fact, some of the most annoying bugs in programs in other languages come from allocating but not releasing memory correctly.
In Java, this is never your concern, because the Java run time system automatically detects when objects are no longer in use and deletes them. Thus, while we can use the new command prolifically to allocate memory as we need it, we never have to concern ourselves with the management of that memory and its subsequent release.
All objects have a finalize method which will be called before the object is deleted and garbage collected. You do not need to release assigned memory but you may want to close open files or network connections in this method. You should end any finalize method by calling super.finalize() to assure that the system cleans up correctly.
If you have been programming in VB, C++ or Pascal,
you are probably familiar with named constants. These are used
whenever you can improve program readability. Named constants
do not change during a program's execution, but you may elect
to change their values during the development of a program.
'In VB Const PI = 3.1416
//In C or C++ const PI = 3.1416;
In Java, values which cannot be changed are said
to be final, and as usual must be members of some class.
If you make reference to such constants, you must refer to the
class they are members of as well. For example, the Math
class contains definitions for both pi and e.
float circumference = 2 * Math.PI * radius;
Similarly, most of the common colors are defined
as RGB constants in the Color class:
setBackground(Color.blue);
You can declare constants by making them final and public if you want to access them from outside the classes.
Class House { public final int GARAGE_DOORS = 2;
Then, whether or not you have a current instance of the House class, you can always refer to this constant:
System.out.println("Doors =" + House.GARAGE_DOORS);
Note also that Java has three "built-in" constants" true, false, and null.
In this chapter, we've learned about the built-in
Java String, StringBuffer and Array classes and how to print out
numbers as strings. We've also touched on Java's automatic garbage
collection and on how to use named constants in classes.
Java and
all Java-based trademarks and logos are trademarks or registered
trademarks of Sun Microsystems, Inc. in the U.S. and other countries.