Written by David Reilly, April 25, 1997
Java provides a rich set of pre-written classes, giving programmers an existing library of code to support files, networking, graphics, and general language routines; each major category being supported by a collection of classes known as a package. I'll be covering each of these packages in a later part of the tutorial series, but for now, will introduce you to one of the most important packages of all - java.lang.
By default, each Java application/applet has access to the java.lang package. Inside java.lang are classes that represent primitive data types (such as int & char), as well as more complex classes. It contains classes pertaining to strings, string buffers, threads, and even the System class from which we obtain out input and output streams. Java.lang is quite extensive, and some aspects (such as threads) can be confusing for those new to the Java language. For this reason, I'll only present the more useful, less complex, parts of this package. This should allow you to experiment with some of the handy features of the Java language, while minimising the barrier to understanding. For more advanced Java programmers, you may wish to consult the Java API yourself, and experiment with other parts of java.lang not covered herein.
We've used some of the simple data types, such as strings and floating point numbers (double), but haven't actually looked at some of their methods. Below, I'll cover some of the more important data types :
In Java, all classes are actually subclasses of class Object. In a previous tutorial, we covered what it meant to extend a class, and the syntax for creating new classes.
When we define a class,
class MyClass
{
.....
}
we are actually implicitly extending MyClass from class Object. Thus, we can replace the
above sample with the following :
class MyClass extends Object
{
.....
}
At first glance, this might not appear to be very important, except for academic interest. However, it actually has a profound impact - every class in Java shares the same properties, and hence methods of class Object. While there are several methods that might be of use, the most important of these is the toString() method.
Every object can be explicitly converted into a string representation, by calling the toString() method which returns a string. Thus, we can explicitly convert objects, such as floating point numbers, integers, etc. If you construct a class yourself, you should consider overriding the toString method, to provide a suitable return value.
double my_double = 3.14;
String my_str = my_double.toString()
The numerical data types all share some common methods, which their inherit from class Number. All numbers are convertible to the basic numerical classes (int, long, float, double) using the following method calls :
int intValue();
long longValue();
float floatValue();
double doubleValue();
Integer, and the longer form, long, represent whole number values. Integers and longs can be interchanged through the longValue() and intValue() methods, and can also be converted to floats and doubles using the floatValue() and doubleValue().
Integer my_integer = new Integer(256);
Long my_long = my_integer.longValue();
Floating point values, and the longer form, double, represent decimal (fractional) values. Floats and doubles can be interchanged through the doubleValue() and floatValue() methods, and can also be converted to integers and longs using the longValue() and intValue() methods. Its important to remember, however, that there will be a loss of precision, as integers and longs cannot retain the fractional component.
Float my_float = new Float(3.14);
Double my_double = new Double (my_float.doubleValue());
// Print out double (3.14)
System.out.println( "Double : " + my_double);
// Print out integer (3)
System.out.println( "Integer: " + my_double.intValue() );
The character class contains a large set of character comparison routines, in the form of static methods. We haven't really discussed static methods before - a static method is a method that is common to all objects of the type that class. In fact, you don't even need to instantiate an object from a class containing a static method to call it!
if (Character.isLowerCase( 'H' ))
{
System.out.println ("Lowercase value detected");
}
else
{
System.out.println ("Uppercase value detected");
}
The character class offers a wide range of character comparison routines; the most useful are listed below :
static boolean isDigit( char c );
static boolean isLetter( char c );
static boolean isLetterOrDigit( char c );
static boolean isLowerCase( char c );
static boolean isUpperCase( char c );
static char toUpperCase( char c );
static char toLowerCase( char c );
Programmers who are familiar with C will understand a string as being an array of characters. Though Java has aspects of C/C++, the definition for a string differs strongly. Under Java, a string is a unique object, which has its own set of methods. Gone are the days of importing a string library, we simply invoke methods of a string object. Some of the more useful routines are listed below :
// Returns the character at offset index
public char charAt(int index);
// Compares string with another, returning 0 if there's a match
public int compareTo(String anotherString);
// Returns a new string equal to anotherString
// appended to the current string
public String concat(String anotherString);
// Returns the length of the current string
public int length();
// Returns true if the current string begins with prefix
public boolean startsWith(String prefix);
// Returns true if the current string ends in suffix
public boolean endsWith(String suffix);
// Returns the remainder of the string, starting from offset beginIndex
public String substring(int beginIndex);
// Returns a substring from offset beginIndex to offset endIndex
public String substring(int beginIndex, int endIndex);
// Returns the current string, converted to lowercase
public String toLowerCase();
// Returns the current string, converted to uppercase
public String toUpperCase();
While strings are extremely useful, there are some tasks that require a more flexible sequence of characters. In cases where strings are being constantly modified, and appended to, it is not always efficient to simply recreate a string every time you wish to concatenate it with another. The StringBuffer class has an append method, which extends the capacity of the StringBuffer when required to accommodate varying lengths. The append method even allows you to add chars, booleans, integers, longs, floats & doubles.
Some of the more useful StringBuffer methods are given below :
// Appends the string version of a boolean to the buffer
public StringBuffer append(boolean b);
// Appends a character to the buffer
public StringBuffer append(char c);
// Appends the string version of a integer to the buffer
public StringBuffer append(int i);
// Appends the string version of a long to the buffer
public StringBuffer append(long l);
// Appends the string version of a float to the buffer
public StringBuffer append(float f);
// Appends the string version of a double to the buffer
public StringBuffer append(double d);
// Appends the string version (toString method) of an object to the buffer
public StringBuffer append(Object obj);
// Appends the string to the buffer
public StringBuffer append(String str);
// Returns the character at offset index
public char charAt(int index);
// Returns the current length of the string buffer
public int length();
// Reverses the order of characters in the string buffer
public StringBuffer reverse();
// Truncates, or pads with null characters, the buffer to a certain length
public void setLength(int newLength);
// Returns a string, representing the string buffer
public String toString();
The System class is perhaps one of the most important classes contained within the java.lang package, as this class provides us with the input and output streams. Without these, it would be very difficult to interact with the user!
public static InputStream in;
public static PrintStream out;
public static PrintStream err;
There is one input stream, and two output streams (out/err). Normal messages should be passed to out, but exceptional cases and error conditions should be written to err (standard error on Unix systems). Since these attributes are static, we need not even instantiate the System class to access them. To print, for example, we can simply use the statement System.out.println()
The System class also has some interesting methods which are of use to Java programmers.
public static void exit(int status)
public static String getProperty(String key);
Exit allows a Java programmer to immediately terminate execution of the program, and to return a status code. By convention, a non-zero status code indicates an error has occurred, and on PC systems, should set the appropriate DOS errorlevel.
If your Java application has been run from a batch file, you can actually test to see if it has executed correctly. Presented below is a test class, and a batch file that when executed will check for a status code of six.
class test
{
public static void main(String args[])
{
System.exit (6);
}
}
Listing 1.0 - Test.java
@echo off
if ERRORLEVEL 6 echo Errorlevel 1 detected
REM Execute test.class
java test
if ERRORLEVEL 6 echo An error has occurred. Please restart
Listing 1.1 - Test.bat
A check is made, in two places, to see if errorlevel six has been set, so that the change in errorlevel can be seen. Its also important to note that an errorlevel will last longer than the duration of the batch file - running test.bat a second time will mean that the first error check returns true.
Another useful method from the System class is getProperty. Via the getProperty method, a Java application can gain information about the operating system under which it is running, the vendor and version of the Java virtual machine, and even the user name and home directory path of the current user under Unix based systems.
Some of the more common system properties are listed in the table below.
Key | Description of associated value |
---|---|
java.version | Java version number |
java.vendor | Java-vendor-specific string |
java.vendor.url | Java vendor URL |
java.home | Java installation directory |
java.class.version | Java class format version number |
java.class.path | Java classpath |
os.name | Operating system name |
os.arch | Operating system architecture |
os.version | Operating system version |
file.separator | File separator ("/" on Unix) |
path.separator | Path separator (":" on Unix) |
line.separator | Line separator ("\n" on Unix) |
user.name | User account name |
user.home | User home directory |
user.dir | User's current working directory |
Table 1.0 - getProperty key/value pairs
Accessing the system properties is as simple as calling the static getProperty method and passing a key from the table as a parameter. An example is shown below, which displays the operating system of the computer it is running on.
class GetPropertyDemo
{
public static void main(String args[])
{
// Display value for key os.name
System.out.println ( System.getProperty("os.name") );
}
}
At the conclusion of this tutorial, you should be more familiar with the java.lang package, and the classes contained within. For extra practice, you should consider writing a few programs of yourself, using number conversion and string manipulation. Practice with the classes in java.lang should prepare you for the next challenge - that of Java's graphical/utility/network packages.