home *** CD-ROM | disk | FTP | other *** search
/ Media Depot 5 / mediadepotvolume51993.iso / FILES / 13 / JAVNL007.ZIP / JAVNL007.TXT < prev   
Encoding:
Text File  |  1996-07-13  |  11.5 KB  |  358 lines

  1. Issue #007
  2. July, 1996
  3.  
  4.  
  5. Contents:
  6.  
  7. Invoking Subprograms in Java
  8. Comparing C/C++ to Java Part 7 - Destructors vs. Finalize
  9. Free Java Library
  10. Enums and Java
  11. Introduction to Applet Programming Part 3 - Events
  12.  
  13.  
  14. INVOKING SUBPROGRAMS IN JAVA
  15.  
  16. It's often the case that when writing programs, you'd like to invoke
  17. another program from within the first and send it input and get output
  18. from it.  How might this be done in Java?  A simple example that runs
  19. the UNIX program "ls" to retrieve a listing of files in the current
  20. directory looks like this:
  21.  
  22.         import java.io.*;
  23.  
  24.         public class test1 {
  25.  
  26.                 public static void main(String args[])
  27.                 {
  28.                         try {
  29.                                 Process cp = Runtime.getRuntime().exec("ls");
  30.                                 DataInputStream d =
  31.                                     new DataInputStream(cp.getInputStream());
  32.                                 String line = null;
  33.                                 while ((line = d.readLine()) != null)
  34.                                         System.out.println(line);
  35.                         }
  36.                         catch (Throwable e) {
  37.                         }
  38.                 }
  39.  
  40.         }
  41.  
  42. The call to exec() starts the process running, and returns a Process
  43. object.  Then we query the Process object to get a buffered input
  44. stream that is connected to the output of the child process.  We then
  45. can simply iterate over this stream, reading lines in turn, that are
  46. the output of ls.  In a similar way, it's possible to send input to
  47. the child process or capture its error output.
  48.  
  49. The Process class has several additional methods available for
  50. controlling processes:
  51.  
  52.         waitFor()       wait for the child process to complete
  53.  
  54.         exitValue()     return the exit value for the process
  55.  
  56.         destroy()       kill the process
  57.  
  58. There is also a variant of exec() that supports passing of environment
  59. variables to the child process.
  60.  
  61.  
  62. COMPARING C/C++ TO JAVA PART 7 - DESTRUCTORS VS. FINALIZE
  63.  
  64. In C++ there is the notion of a destructor, a function called when a
  65. class object instance goes out of scope.  For example:
  66.  
  67.         class A {
  68.         public:
  69.                 A();
  70.                 ~A();
  71.         };
  72.  
  73.         void f()
  74.         {
  75.                 A a;
  76.         }
  77.  
  78. When the function f() is entered, the constructor A::A() is called for
  79. the local object a, and when f() is exited, the destructor A::~A() is
  80. called in turn.
  81.  
  82. Java class objects do not behave in a similar way.  They are
  83. dynamically allocated, at which point a constructor is run on the
  84. object instance, and later garbage collected.
  85.  
  86. Java does not have any notion of a destructor method that is run when
  87. an object instance is no longer valid.  But it does have a finalize()
  88. method:
  89.  
  90.         protected void finalize() {}
  91.  
  92. that can be added to any class.  finalize() is called for an object
  93. instance after that instance has been identified by the garbage
  94. collector as no longer a valid object, that is, there are no remaining
  95. references to it.  For example:
  96.  
  97.         public class test1 {
  98.  
  99.                 public test1()
  100.                 {
  101.                         System.out.println("call ctor");
  102.                 }
  103.  
  104.                 protected void finalize()
  105.                 {
  106.                         System.err.println("call finalize");
  107.                 }
  108.  
  109.                 public static void f()
  110.                 {
  111.                         test1 p = new test1();
  112.                 }
  113.  
  114.                 public static void main(String args[])
  115.                 {
  116.                         f();
  117.                         System.gc();
  118.                         System.runFinalization();
  119.                 }
  120.         }
  121.  
  122. After the return from the f() call, there is an object instance that
  123. can be garbage collected; there is no reference to the object we
  124. created while inside of f().
  125.  
  126. System.gc() frees up objects and marks them as pending for
  127. finalization to be done.  Actual finalization processing proceeds
  128. asynchronously with the garbage collector, so to force finalization we
  129. can call System.runFinalization().
  130.  
  131. Because of the way that finalize() methods work, you should use
  132. caution in assuming that they can be used to reclaim valuable
  133. resources such as UNIX file descriptors.  Also, you should insert a
  134. line like:
  135.  
  136.         super.finalize();
  137.  
  138. at the end of a finalize() method, to call the corresponding method of
  139. the superclass.
  140.  
  141.  
  142. FREE JAVA LIBRARY
  143.  
  144. I have developed a Java library for managing collections of objects,
  145. such as lists, stacks, sets, bitmaps, and trees.  If you are
  146. interested in this library, please see the Web page:
  147.  
  148.         http://rmi.net/~glenm/javalib/index.html
  149.  
  150.  
  151. ENUMS AND JAVA
  152.  
  153. In C++ there is a facility known as enumerations or enumerated types
  154. that can be used to represent a set of integral values:
  155.  
  156.         enum Color {CO_R = 1, CO_G = 2, CO_B = 3};
  157.  
  158. After this declaration, Color can be used as a type (including for
  159. function overloading purposes), and values like CO_R can be used
  160. wherever integral constants would be used.  Type checking is done, so
  161. that for example:
  162.  
  163.         Color c = CO_R;
  164.  
  165.         c = 37;
  166.  
  167. is invalid.
  168.  
  169. Java does not have enumerations.  One way to simulate them is simply
  170. by defining constants in a class:
  171.  
  172.         public class Color {
  173.                 public static final byte CO_R = 1;
  174.                 public static final byte CO_G = 2;
  175.                 public static final byte CO_B = 3;
  176.         };
  177.  
  178. public means that these values are accessible to all, static means
  179. that they're shared across all object instances, final means that
  180. they're immutable once set, and byte means that they're represented in
  181. bytes in the virtual Java machine.
  182.  
  183. Once a class like this is set up, you can say things like:
  184.  
  185.         byte b = Color.CO_G;
  186.  
  187. But notice that this simulation is only a simulation.  There's nothing
  188. to stop me from saying:
  189.  
  190.         byte b = Color.CO_R;
  191.         b = 29;
  192.  
  193. and thereby introduce an invalid color value.  A solution to this
  194. problem would be to define Color as a "real" class, that represents
  195. the actual current value of an enumeration:
  196.  
  197.         public class Color {
  198.                 private byte value = 0;
  199.                 public static final byte CO_R = 1;
  200.                 public static final byte CO_G = 2;
  201.                 public static final byte CO_B = 3;
  202.                 public Color(byte b)
  203.                 {
  204.                         if (b == CO_R || b == CO_G || b == CO_B)
  205.                                 value = b;
  206.                         else
  207.                                 throw new IllegalArgumentException();
  208.                 }
  209.                 public byte getvalue()
  210.                 {
  211.                         return value;
  212.                 }
  213.         }
  214.  
  215. This approach works, but can be cumbersome to use.  However, enums,
  216. like other language features, add to the total complexity and
  217. implementation cost of a language, and leaving them out of Java is a
  218. reasonable design tradeoff to make.
  219.  
  220.  
  221. INTRODUCTION TO APPLET PROGRAMMING PART 3 - EVENTS
  222.  
  223. In previous issues we've talked about the basic protocols underlying
  224. an applet and how graphical and text output is done.  With this issue
  225. we'll start a discussion of input handling, and begin by talking about
  226. events just a little bit.
  227.  
  228. Here is an applet that allows a user to do free drawing with the
  229. mouse.  That is, whenever the mouse button is held down and the mouse
  230. moved, a line will be drawn:
  231.  
  232.         import java.applet.*;
  233.         import java.awt.*;
  234.  
  235.         public class Draw extends Applet {
  236.  
  237.                 int prev_x = 0;
  238.                 int prev_y = 0;
  239.                 int color = 0;
  240.  
  241.                 public boolean mouseDown(Event e, int x, int y)
  242.                 {
  243.                         prev_x = x;
  244.                         prev_y = y;
  245.                         return true;
  246.                 }
  247.  
  248.                 public boolean mouseDrag(Event e, int x, int y)
  249.                 {
  250.                         Graphics g = getGraphics();
  251.  
  252.                         switch (color) {
  253.                                 case 0:
  254.                                         g.setColor(Color.red);
  255.                                         break;
  256.                                 case 1:
  257.                                         g.setColor(Color.green);
  258.                                         break;
  259.                                 case 2:
  260.                                         g.setColor(Color.blue);
  261.                                         break;
  262.                         }
  263.                         if (++color > 2)
  264.                                 color = 0;
  265.  
  266.                         g.drawLine(prev_x, prev_y, x, y);
  267.                         prev_x = x;
  268.                         prev_y = y;
  269.                         return true;
  270.                 }
  271.         }
  272.  
  273. This applet can be invoked via the HTML code:
  274.  
  275.         <html>
  276.         <head>
  277.         <title>Interface to Draw Applet</title>
  278.         </head>
  279.  
  280.         <body>
  281.  
  282.         <applet code="Draw.class" width=400 height=400></applet>
  283.  
  284.         </body>
  285.         </html>
  286.  
  287. using the JDK AppletViewer program.
  288.  
  289. We've alternated the output color of the drawn line, as a means of
  290. tying together some of the ideas from the last issue, and to better
  291. illustrate what is happening.
  292.  
  293. mouseDown() is an applet method called by the system when the user
  294. presses a mouse button.  It's passed a description of the event along
  295. with an X,Y pair, and returns true if it handled the event, so that
  296. the event will not be further processed.  In our example we simply
  297. record the X,Y location where the event occurred.
  298.  
  299. mouseDrag() is a method called when the user drags the mouse with the
  300. button down.  When this occurs, we switch colors and then draw a line
  301. between the old position and the new one.  getGraphics() is a method
  302. that returns a java.awt.Graphics object, that is used for line
  303. drawing, image painting, and so on.
  304.  
  305. If you run the above applet, the colors will alternate very rapidly if
  306. you move the mouse slowly, and alternate more slowly if you move the
  307. mouse rapidly.  Why is this?  It has to do with polling of the mouse.
  308. That is, the mouse's status is checked at regular intervals.  If the
  309. mouse has moved a long ways in the poll interval, then the
  310. single-color line segment will be longer than if the mouse had been
  311. moved slowly.
  312.  
  313. We will be discussing events and input further in upcoming issues.
  314.  
  315.  
  316. ACKNOWLEDGEMENTS
  317.  
  318. Thanks to Thierry Ciot, Irv Kanode, Mike Paluka, and Alan Saldanha for
  319. help with proofreading.
  320.  
  321.  
  322. SUBSCRIPTION INFORMATION / BACK ISSUES
  323.  
  324. To subscribe to the newsletter, send mail to majordomo@world.std.com
  325. with this line as its message body:
  326.  
  327. subscribe java_letter
  328.  
  329. Back issues are available via FTP from:
  330.  
  331.         rmii.com /pub2/glenm/javalett
  332.  
  333. or on the Web at:
  334.  
  335.         http://www.rmii.com/~glenm
  336.  
  337. There is also a C++ newsletter.  To subscribe to it, say:
  338.  
  339. subscribe c_plus_plus
  340.  
  341. using the same majordomo@world.std.com address.
  342.  
  343. -------------------------
  344.  
  345. Copyright (c) 1996 Glen McCluskey.  All Rights Reserved.
  346.  
  347. This newsletter may be further distributed provided that it is copied
  348. in its entirety, including the newsletter number at the top and the
  349. copyright and contact information at the bottom.
  350.  
  351. Glen McCluskey & Associates
  352. Professional Computer Consulting
  353. Internet: glenm@glenmccl.com
  354. Phone: (800) 722-1613 or (970) 490-2462
  355. Fax: (970) 490-2463
  356. FTP: rmii.com /pub2/glenm/javalett (for back issues)
  357. Web: http://www.rmii.com/~glenm
  358.