Common Coding Situations in Java

Common Coding Situations in Java


 This blog contains some snippets of code that I tend to use in Java.  I acknowledge that somebody else writing this blog might include different code.  Except for a short course at Sun Educational Services, most of my Java programming skills are self-taught.  I’m unsure if people with formal backgrounds in computer science might have different styles and conventions.  Mine have been shaped primarily by my needs.

Creating a Graphical User Interface (GUI)

In this blog, I use the term “interface” to describe a screen that the user uses in order to interact with the program; this is also known as a GUI.  I faintly recall that the term “interface” from a coding standpoint on Java has a more specific meaning; but I am invoking the vernacular sense of the term.  I am a fairly lazy user-interface developer these days.  I tend to use whatever fields, buttons, panels, and text fields are available on the platform.  Perhaps as a further sign of my lack of discipline, I don’t even bother documenting or memorizing the mandatory lines required by Java to enable its interface components.  I literally allow the compiler to give me error messages until all of the necessary lines have been added.  Below, as the image of a particular interface I created shows, the user is free to construct his or her components.  Alternatively, there are platform-independent components available from Java itself.

In general – except maybe for content or entry validation purposes – no calculations should be done on the code for the interface.  If lengthy calculations are performed from the GUI, it might struggle to update or refresh; and it might stop responding to user input completely.  This problem should be of particular concern to data scientists.  Below I share the code simply to close the window.  It is the implementation of WindowListener (the interface) that creates the need for the methods like windowClosed(), windowDeactivated(), and windowDeiconified.  At some point during the construction of the user interface, it is necessary to invoke “addWindowListener(this)”; this will cause the program to actually listen to the window.

import java.awt.*;
import java.awt.event.*;

public class Facade extends Frame implements WindowListener {
     public Facade() {}

     public void windowClosed(WindowEvent e) {}
     public void windowActivated(WindowEvent e) {}
     public void windowDeactivated(WindowEvent e) {}
     public void windowDeiconified(WindowEvent e) {}
     public void windowIconified(WindowEvent e) {}
     public void windowOpened(WindowEvent e) {}
     public void windowClosing(WindowEvent e) {}
}

During the early years of Java, there was a completely different way of causing the GUI to respond to the user.  I remember that mixing the two methods caused my programs to crash hard.  However, since the change, I have personally found the GUIs exceptionally stable.  The only problem might be forgetting to handle user input:  e.g. actually closing the window after the user clicks a button that says “Close Window.”  Then I have to use Taskmaster to close the program.

Executing a System Command During Runtime

I routinely invoke Notepad on Windows to open a file containing text.  It is possible I just generated the file; or perhaps I recently updated it.  During diagnostics, I normally have my programs retain one or several runtime logs, which I sometimes cause to open automatically after the program has finished running or in the event of questionable events.  Also rather frequently, I make Windows open spreadsheets and HTML files after they are compiled.

     public void notepad(String s) {
          command(“Notepad “” + s + “””);
     }

     public void send(String s) {
          command(“Explorer “” + s + “””);
     }

     public void command(String s) {
          try {
               System.out.println(“Command sent: ” + s);
                (Runtime.getRuntime()).exec(s);
          }
          catch(IOException x) {
               System.out.println(“Exception raised”);
          }
     }

So using the above, I would invoke the method notepad(myPathAndFile) where myPathAndFile is the name of the path and file that I want to open using Notepad.  Those that have never passed a system command in this manner might find the level of functionality surprisingly reliable.  When the path or filename contains spaces – or even if I just want to be consistent – quotes should be made to surround myPathAndFile; this occurs before the command() method is called as per the code snippet.

Converting a String to a Number

When I was first learning Java, I had difficulty “properly” converting strings into numbers.  I remember during my Java course, the instructor either didn’t have all of the information; or he wasn’t prepared to share it.  The user needs to invoke an intermediary.  Below, I use Double() to facilitate the conversion to a double.

     public double getValue(String in) {
          if(in != null) {
               try {
                    return (new Double(in)).doubleValue();
               }
               catch(NumberFormatException e) {
               }
          }
          return 0;
     }

What if the string isn’t in the correct format: e.g. “hello world!” rather than “123.456”?  The program might crash if the error isn’t caught and handled in an acceptable manner.  In the method above, in the event of error, 0 is returned.  (Returning a 0 is not always a good idea.)  The above code snippet leads one to question, how does a person convert a number into a string?

     /* Here is an explicit approach */
     String myString = String.valueOf(myNumber);

     /* This is implicit */
     String myString = “The number is:” + myNumber;

Reading and Writing Lines of Text

What exactly is the best way to access text files in Java?  I thought about sharing the class that I use most often.  I would say that the code I use is definitely confusing.  This is due to the ability to include a number of files in the filename – allowing for seamless extraction.  So I want to approach the question more conceptually.

I suggest that FileInputStream and FileOutputStream are much faster than using RandomAccessFile.  Moreover, it is better to handle data on a line-by-line basis rather than loading everything all at once and manipulating large strings in RAM.  These preferences of mine developed during the early years of Java and also Windows.  I am uncertain if Java would still perform better based on my preferences today on different platforms.
In order to convert a buffer of bytes into a string, refer to the code below.  The string “loaded” will accumulate text-encoded bytes from “buffer.”

     try {
          int size = input.read(buffer);

          if(size > 0) loaded += new String(buffer, 0, size);
          else {
               input.close();
          }

     }
     catch(IOException e) {
     }

My bias also affects how I save documents.  I much prefer to do incremental saves rather than save a huge string all at once at the end of processing.  In effect, my programs tend to require minimal computing resources.  When I was younger, RAM was much less abundant than it is today; and perhaps these days it isn’t necessary to be cautious about using too much RAM during runtime.  A leopard has a difficult time changing its spots, I suppose.
 
Running Calculations on Separate Threads

In order to support complex operations – and also to keep things neat – coding should be made to run on separate threads.  This will prevent the computer program from hogging up resources.  Nothing is more troubling than the GUI stalling or failing to respond to clicks because of busy operations.  A common reason to support separate threads is to allow operations to be paused or aborted.  I personally consider the spawning a threads a pretty diverse subject.  The entire class should implement Runnable.  In order to start the program, call start(); and of course to stop the program use stop(); or make T = null.  The pause at run() is optional; but to me it hardly makes sense to spawn separate threads without deliberately taking control over the processing rate.

public class MyProgram implements Runnable {
     Thread T = null;

     public myProgram() {
     }

     public void pause(int n) {
          try {
               T.sleep(n);
          }
          catch(InterruptedException e) {}
     }

     public void start() {
          if(T == null) {
               T = new Thread(this);
               T.start();
          }
     }

     public void stop() {
          T = null;
     }

     public void run() {
          if(T != null) {
               /* Take a breather after doing something interesting */
               pause(10);
          }
     }

}

Now, running a thread and making it interact with other parts of the program requires some technique.  For example, the thread might complete its operations 60 minutes in the future; presumably it should notify the user or commence some other operation at that point.  There are a few techniques the thread can use:  1) leave a calling card notifying the main or supra program that it has finished running; 2) invoke a method in the main or supra program assuming the user has passed a reference to it for the thread to invoke; or 3) give the thread an “invoker” – to invoke a method upon completion but without an explicit reference.  I don’t recall Java having a built-in invoker class for the purpose described here.  I created one just to be different.  Suffice it to say that a person has to give threads a lot of planning.

So those are common coding situations that I encounter in Java.  By no means am I an ardent proponent of Java.  People should use whatever language makes sense in terms of their situation.  Java is not an “easy” language to learn.  But I did mention that most of my skills are self-taught.  Check out the fractal-sequencing comparison of a sawtooth waveform I generated below:  using reluctant sentiment; random containment; and based on actual chimpanzee DNA.  This is just my way of emphasizing that the language isn’t “really difficult” to learn.  I believe that the program that generated the image – i.e. rendered the image – makes use of some or possibly all of the code snippets mentioned in this blog.


Link: Common Coding Situations in Java