Test of the function System.out.println:

In class, I said that println could not directly print a double, without converting explicitly to a String, but that is not true. Here is the file TestPrintln.java:

// TestPrintln.java: test printing of types with println
public class TestPrintln
{
   public static void main (String[] args)
   {
      // boolean.
      boolean x = true;
      System.out.println(x);

      // char.
      char   c = 'A';
      System.out.println(c);

      // double.  Works without the D below.  Still a double
      double y = 3.141592653589792D;
      System.out.println(y);

      // float.  An error without the F or the cast (float) below
      float  z = 3.141592653589792F;
      System.out.println(z);

      // int.
      int    i = 2123123123;
      System.out.println(i);

      // long.  An error with the L below
      long   k = 123456789123456789L;
      System.out.println(k);

      // char[], an array of char.
      char[] s = {'A','n',' ','a','r','r','a','y'};
      System.out.println(s);

      // Double.  putting a double in a "wrapper" class
      Double w = new Double(y);
      System.out.println(w);

      // AnyOldClass.  (just a random class, as long as it
      //    has a public method toString, with no input parameters
      //    that returns String)
      AnyOldClass a = new AnyOldClass();
      System.out.println(a);
   }
}
// AnyOldClass:  This class is in the same file with TestPrintln.  If it
//   is put in a separate file (as we normally do), then it must have "public"
//   in front of "class", and the file must be named "AnyOldClass.java
class AnyOldClass {
   private int i = 47;
   public String toString() {
      return "Inside AnyOldClass " + i;
   }
}

Here is the output when the Java program is run:

true
A
3.141592653589792
3.1415927
2123123123
123456789123456789
An array
3.141592653589792
Inside AnyOldClass 47


Revision date: 2001-01-25. (Please use ISO 8601, the International Standard.)