EXAMPLES

PIC 20A/1, Summer 2001


  1. The very first example, traditional "Hello World!" program:
  2. A first Applet, example is cited from The Java Tutorial: a spot appears when you click the mouse within the applet's bounds: The source files for the applet: Certainly, to run the applet, you also need to create and HTML file with appropriate APPLET tag in it (see the source of the ClickMe.html above). A slight modification of the above applet: ClickMe2.
  3. Class Echo demonstrates how to pass command line arguments into a Java program. Command line arguments are treated as elements of an array of strings, conventionally named args. A slight modification of the Echo program shows how to address individual characters in a string. Class Reverse prints out command line argumets in reverse. Here is a sample output of these programs:
    > java Echo hello my dear
    > hello my dear
    > 
    > java Reverse hello my dear
    > raed ym olleh
    
  4. The program ContinueWithLabel demonstrates labeled versions of break and continue statements. These allow us to break out of (or, respectively, to continue with) an outer loop in a series of nested loops. The program uses some methods from the String class:
  5. The program Palindrome determines whether a string is a palindrome. This program uses many methods from the String and StringBuffer classes. The program also demonstrates how to set up text console based interactive input using BufferedReader class. (Note that another possibility to set up interactive input is to use JOptionPane.showInputDialog() discussed in the D&D textbook. To be consistent one also needs to rewrite all program dialogs to use JOptionPane class then.)
  6. These examples demonstrate Java Exception Handling mechanism. Along the way we introduce some additional classes from the Java API. Class Factorial defines factorial() method which uses caching technique to optimize repeated computations of factorials. The cache is implemented not as a fixed-size array, but as an instance of java.util.Vector class, which gives us an array-like data structure that can grow on demand. Since factorials quickly become very large, we use class java.math.BigInteger, that is designed to represent arbitrarily-large integer values and provides methods to perform arithmetic operations on them. Because factorials are defined only for non-negative integers, the factorial() throws an exception if its argument is a negative integer. A simple main() method provided just as a driver to test the factorial() method. Class FactCalculator is a stand-alone interactive GUI program, that allows user to compute factorials repeatedly. It uses javax.swing.JOptionPane class to communicate with the user. In order to protect the user (from his/her own mistakes), the program tries to CATCH all possible EXCEPTIONS that might arise because of bad input.
  7. Class ListOfNumbers gives yet another demonstration of exception handling in Java. In particular the difference between so-called runtime exceptions and checked exceptions. The latter should be either caught or explicitly declared by a method which can throw them, while the former do not require such explicit handling. Explicit handling of checked exceptions is enforced by the Java platform. (Note that this class does not define a stand-alone program, since it does not have main() method. To test it one needs to write a separate driver.)
  8. An example based on LinkedList class suggested in D. Flanagan, "Java Examples in a Nutshell". It demonstrates many specific features of Java OOP (such as interfaces and nested classes, for example).
  9. A sample solution to the celebrated Homework Project #2:
  10. First two examples of simple Swing GUI programs. Both demonstrate the most essential features of any application based on Swing API.
  11. A modification of our first Swing example above. Except for two lines, the entire code was generated by Forte for Java. One can trace the work of the IDE (Integrated Development Environment) by looking at extra comments it left behind. Please notice that this version of HelloWorldSwing directly extends the JFrame and performs all frame initialization in constructor and methods called from constructor. This makes main() method very simple and straightforward.
  12. A sample solution to the celebrated Homework Project #4:
  13. Three good examples from The Java Tutorial demonstrating Life Cycle of an Applet, along with responce to mouse events and other simple features. To run all three applets, please see Simple.html.
  14. This applet allows user to plot f(x) = x * sin( 1/xa ) for any decimal value of exponent a , where -10 < a < 10 . User can specify the desired exponent and the horizontal range of the graph: -b < x < b . The applet automatically adjusts the vertical range -c < y < c of the graph in accordance with the chosen horizontal range of the graph, so that maximum and minimum of the current function fit within the plotting area. In addition to the graph of the function, the applet plots coordinate axes in a different color. User can repeat plotting with different parameters any number of times. Finally, this applet can be also run as a stand-alone application, without any browser support.
  15. A sample solution to the celebrated Homework Project #5: In order to demonstrate the sample in action, I have precompiled and archived all its class files into a jar file (short for java archive): colorswitch.jar To run the archived application, please download colorswitch.jar and issue the following command from the directory into which you downloaded the jar file:
        java -jar colorswitch.jar
        
    Alternatively, if the above does not work, you can first unpack the archive and then run the application:
        jar xvf colorswitch.jar
        java  ColorSwitch
        
    The source code will be posted here:
  16. Two great multithreaded applets from The Java Tutorial:
  17. A multithreaded applet that continuously runs two threads of randomly choosen priorities. One thread sleeps for 1000 milliseconds before printing the current time, while the other sleeps for 1500 milliseconds before printing the current time. After printing the time, each thread tries to go to sleep again. This cycle is repeat until the applet stops. Each thread is given a name. The name and current priority level of each thread are printed along with its time. In addition to different names, the two threads use different colors for printing (red and blue). All class files of the applet (i.e. files generated by compilation of ThreadsDemo.java) are packed into a single java archive file threadsdemo.jar. When a browser runs the applet, it loads the necessary classes from this jar file.
  18. An example from The Java Tutorial of so-called Producer/Consumer situation, which illustrates Threads Synchronization related issues.
  19. Two Java Tutorial examples of Timer and TimerTask classes which are useful when you want to perform a task repeatedly or after a delay. These classes were added to version 1.3 of Java2 platform.


Last modified on by fedandr@math.ucla.edu.