Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 3 of 5
Listing 2. Type.java
// Type.java
class Type
{
public static void main (String [] args) throws java.io.IOException
{
int ch;
while ((ch = System.in.read ()) != -1)
System.out.print ((char) ch);
}
}
Type resembles Echo, however, there is no prompt, and the while loop tests against -1 (which indicates end of file) instead of \n (which indicates end of line). To run Type, issue the following command line: java Type <Type.java. The contents of Type.java -- or whatever file is specified -- will display. As an experiment, try specifying java Type. What do you think will happen? (Hint: this program resembles Echo but doesn't end until you press Ctrl+C.)
Earlier, I mentioned that some programmers mistakenly think that System.in.read() returns a user-entered number. As you've just seen, that isn't the case. But what must you do if you want to use System.in.read() to retrieve a number? Take a look at the Convert application, whose source code is presented in Listing 3.
Listing 3. Convert.java
// Convert.java
class Convert
{
public static void main (String [] args) throws java.io.IOException
{
System.out.print ("Please enter a number: ");
int num = 0;
int ch;
while ((ch = System.in.read ()) != '\n')
if (ch >= '0' && ch <= '9')
{
num *= 10;
num += ch - '0';
}
else
break;
System.out.println ("num = " + num);
System.out.println ("num squared = " + num * num);
}
}
Listing 3's Convert program prompts the user to enter a number (via System.out.print ("Please enter a number: ");). It reads these digits -- one at a time -- and converts each digit's numeric code to a binary number that is added to a
variable called num. Finally, calls to System.out.println() output the value inside num and the square of that value to the standard output device.
Convert demonstrates the time-honored technique of using a while loop to test for a digit, premultiplying a variable by 10 (to make
room for the incoming digit), converting a digit to its binary equivalent, and adding that binary equivalent to the variable.
However, that technique is not a sound technique to use if you're writing a program for deployment in different countries
as some countries use digits other than 0 through 9 -- such as Tamil digits. To make the program operate with other digits,
you need to expand the if statement to test for those digits and modify the ch - '0' expression. Fortunately, Java simplifies that task by providing a Character class, which you'll explore in a future article.
The standard output device is that part of the operating system that controls where a program sends its output. By default, the standard output device sends the output to a device driver attached to the screen. However, the output destination can be redirected to a device driver attached to a file or printer, which results in the same program displaying its findings on the screen, saving them in a file, or providing a hardcopy listing of the results.
You achieve standard output by calling Java's System.out.print() and System.out.println() methods. Except for the fact that print() methods don't output a new-line character after the data, the two method groups are equivalent. Methods exist to output Boolean,
character, character array, double-precision floating-point, floating-point, integer, long integer, string, and object values.
To demonstrate these methods, Listing 4 presents source code to the Print application.
Listing 4. Print.java
// Print.java
class Print
{
public static void main (String [] args)
{
boolean b = true;
System.out.println (b);
char c = 'A';
System.out.println (c);
char [] carray = { 'A', 'B', 'C' };
System.out.println (carray);
double d = 3.5;
System.out.println (d);
float f = -9.3f;
System.out.println (f);
int i = 'X';
System.out.println (i);
long l = 9000000;
System.out.println (l);
String s = "abc";
System.out.println (s);
System.out.println (new Print ());
}
}
Listing 4 has probably triggered some questions for you. First, what is all that System.out. business doing in front of println()? Again, refer to the System class in the SDK documentation. The class contains a variable called out -- an object created from a class called PrintStream. The period character after System indicates that out belongs to System. The period character after out states that println() belongs to out. In other words, println() is a method that belongs to an object called out, which in turn belongs to a class called System.
The second question you might be asking yourself involves println() argument data types: how is it possible for the same println() method to be called with different types of argument data? The answer: because there are several println() methods in the PrintStream class. At runtime, the JVM knows which println() method to call by examining the number of method-call arguments and their data types. (Declaring several methods with the
same name but different numbers of arguments and argument data types is known as method overloading. I will discuss that concept
next month.)
Finally, you might be wondering about System.out.println (new Print ());. That method call illustrates the println() method, which takes an Object argument. First, the creation operator new creates an object from the Print class and returns a reference to -- also known as the address of -- that object. Finally, that address passes as an argument
to the println() method, which takes an Object argument. The method converts the object's contents to a string and outputs that string. By default, the string consists
of the name of the object's class, followed by an @ (at) character, followed by a hexadecimal-formatted integer that represents the object's hashcode. (I will present hashcodes
and the conversion of objects to strings in an upcoming article.)
Compile Print.java and run the program by issuing the following command line: java Print. You should see nine lines of output. Redirect that output to the out.dat file by issuing the following command line: java Print >out.dat. You can now view the contents of the file.
The greater-than sign, >, indicates standard output redirection. Whenever you want to redirect the standard output device from the screen to a file
or printer, specify that symbol followed by the file or printer name on the command line. For example, redirect Print's output to a Windows printer by issuing the following command line: java Print >prn.
The PrintStream class provides a println() method, which takes no arguments. That method outputs a single new-line character. Behind the scenes, the various println() methods call their print() method counterparts followed by the no-argument println() method. A close look at the documentation for the no-argument println() method shows the new-line character being obtained from a system property called line.separator. That system property's value is not necessarily the same as \n. (I will discuss system properties in a future article.) To seek true platform independence, don't hard-code \n in your print() or println() arguments. (In this course, the \n literal is often specified in source code.)