Cephi Systems Software and Contract Services

25Dec/112

Simple Java Applet

Java applets are a somewhat dead technology. Many have hoped for years that they would get a face-lift someday. They are easy to use and you can do a lot with them, wherein one language can be used server side and client side. I am starting to think with the rise of HTML5 applets may never return. As of this writing only about 37% of all computers used for surfing the web have Java loaded per Riastats.com. This makes choosing a Java applet as the main technology for your web application a rather poor choice unless you know ahead of time that all of your users will have Java installed.

A couple of ways to get a Java applet on a WordPress page are with the following WordPress plugins:

  • Java Applet Embed (I haven't tested this one)
  • Page View - link an HTML page with a applet link on it

Below is an example of a simple Java Applet:

10May/112

JavaScript from Java: Google Web Toolkit – GWT

Programming for the web is a bit like creating a Frankenstein monster. It is an amalgamation of different technologies that weren’t always created to work together. It reminds me of Marry Shelly’s shambling monstrosity in that it is composed of seemingly unrelated parts, crudely sewn together to create something that ends up working somehow.

I imagine if web programming was reimagined and reinvented today there would be one language encompassing all the functionality of HTML, CSS, XML, JavaScript, and PHP/Ruby. You could even throw in C#/Java (or your favorite high level language), and some SQL, so you could do everything with one language.

All this will probably only happen in some dystopian future sometime after the English language is reengineered to be more efficient, consistent, and structured. That would be doubleplusgood, no?

Well enough philosophizing and on to some Google Web Toolkit goodness… I guess I could have titled this article “Google Web Toolkit: So you know some Java and you want to do some client-side web programming?”

Google Web Toolkit (GWT) is a set of development tools that includes a GUI designer for creating Ajax applications (client-side, interactive web applications than run on a browser). GWT allows you to write a program in Java and then compile them into a combination of JavaScript, HTML, and CSS. GWT is compatible with all the major browsers and is available as a stand-alone SDK or as a plug-in for Eclipse. I used the Eclipse plug-in.

I am not here to evangelize GWT, but rather to provide a Java developer’s initial opinion on and experience with the technology.

If you have some experience with Java, one nice thing about GWT is that you don’t need to learn JavaScript to produce a client-side web applications. The calculator application I wrote (see link at the bottom) required no use of JavaScript whatsoever on my part. The compiler did all the work for me.

GWT has the advantage over Flash in that GWT just requires a web browser, no plug-ins needed. So far the apps I have created with GWT have worked great on all the mobile devices I tested them on. Flash does not work on iOS, and has mixed results on Android.

Personally, I find that I can develop client side applications a lot quicker in GWT than in HTML/CSS/JavaScript. Normally you would create buttons, input boxes, and labels in HTML, format them for appearance and graphical behavior in CSS, then do some simple programming for the functionality of the application in JavaScript. The nice thing about GWT you can do most of this all in one place, in one language. You can then test and compile your application in the IDE, and it is pretty easy to deploy all the files to your server.

The SDK generates HTML and CSS pages for you but the HTML page requires a little configuring. Also to include any fancy formatting you have to modify the CSS page. For my calculator app I just changed a couple of titles and included a division to specify where to insert the app on the page with id="GWTCalcGoesHere". Google’s tutorial explains how to do all this.

On the negative side, I imagine that GWT can be likened to Dreamweaver (or a high level programming language) wherein the code produced is typically less compact and efficient than code written manually in the underlying technology. How significant the difference is, I don’t know. As with every programming technology there is a tradeoff between development time and cost vs. performance of the end product.

If you are already good at JavaScript (and enjoy using it) I would say stay with JavaScript. If you are good with Java and you want to write some client-side apps without fooling around with a lot of HTML, and JavaScript, GWT may be worth your time checking out.

To get started with GWT I recommend visiting Google’s GWT page, installing the software, and doing their StockWatcher tutorial. You can skip the CSS steps if you are not interested in making it look pretty. It only took me a couple of hours to get GWT installed, read the introductions, and do the tutorial. Then it took a few more hours to get comfortable with the libraries, and write a couple of apps. Assuming you developed a fair proficiency with Java, learning GWT should be pretty easy.

Although the bulk of the libraries I have worked with are from GWT and not JRE, GWT does a good job of keeping things Java-like so it is easy to find the method names you are looking for. The syntax is the same and for the simple projects I worked on it pretty much feels like you are writing a Java app when working with GWT. The GWT online documentation even closely resembles the Oracle API documentation for Java, so there is no new learning curve. I do wish it included more code examples but this can be said for any programming language’s online documentation.

(Google, if you are reading this I would be happy to write billions of code snippets for you at a highly affordable price.)

So below is the link to the simple calculator application and source code I wrote using the GWT plug-in for Eclipse:

GWT Calcualtor

I wouldn’t look at this as a shining example of great program construction, but rather a peek into a little of what GWT can do. Overall I found GWT to be enjoyable to use.

25Apr/110

Java Article 24: Constants and the DRY Principle

Constants are a variety of static fields in Java. Constants are aptly named: They are intended to represent one immutable value, i.e. they are constant.

Constants are convenient because you can specify a value in one place verses specifying the value every time you need it. Also constants prevent you or another programmer from unintentionally changing the constant’s value somewhere else int he program. The use of constants is common in all kinds of software applications, especially in scientific and engineering applications, where you could be working with something like the ideal gas law.

Below are a couple of methods from an application calculating pressure and temperature with the ideal gas law:

public static double calculatePressure(double numberOfMoles,
double temperatureKelvin, double volumeLiters)
{
//Pressure = nRT / V
double pressurePascals =
(numberOfMoles * 8.314472 * temperatureKelvin )
/ volumeLiters;

return pressurePascals;
}

public static double calculateTemperature(double pressurePascals,
double volumeLiters, double numberOfMoles)
{
//Temperature = PV / nR
double temperatureKelvin =
(pressurePascals * volumeLiters)
/ (numberOfMoles * 8.314472 );

return temperatureKelvin;
}

Instead of entering the 8.314472 each time the value for R is needed you could declare it as a constant since you expect this value to never change. You do this by using:

public static final double IDEAL_GAS_CONSTANT = 8.314472;

The naming convention for constants is all caps with underscores between words. This helps you and other programmers identify them easily. The constant’s declaration uses the modifier static (meaning it is associated with a class rather than just an object), and the modifier final. The final modifier is what makes the constant immutable, as demonstrated below:

public class MainClass
{

public static final double IDEAL_GAS_CONSTANT = 8.314472;

public static void main(String[] args)
{
IDEAL_GAS_CONSTANT = 34.333; //error: this can not be changed
}

}

The use of constants is also a very basic example of using the Don't Repeat Yourself (DRY) principle of software development put forth by Hunt and Thomas in The Pragmatic Programmer. The DRY principle states "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."

In our example if you were to enter 8.314472 throughout your program you could make a typo resulting in a calculation error. Possibly even with dangerous consequences since we are working with gasses under pressure.

Using the constant IDEAL_GAS_CONSTANT is less prone for error. Typically if you make a typo here you get a “cannot be resolved” error from the compiler.

Another reason it is good to use constants is if a user came back and told you they needed a constant changed so the software performs better. Suppose you have a value in 20 different places in your program. First, it is much faster to change the value of one constant than it is to change the value in 20 different places.

Second, suppose you are changing the values and you only end up changing 19 of them, missing one. This type of error is very common in both programming and technical writing. Following the DRY principle helps prevent this kind of error.

Another reason to use constants is that constants are evaluated at compile time, while other variables are evaluated at run time. Using constants will give you a slight performance boost.

Depending on the architecture and complexity of your program you can declare your constants in different places:

  • If you have only one class, put your constants in that class.
  • If you have many classes needing the constants, put the constants in their own class or even multiple classes.*
  • If your constants are sets of named values like days of the week, or car models and their weights consider using an enum.
  • You should also plan for future growth (extensibility). If you think it is likely the number of classes in your program will grow, and additional classes will need your constants, put the constants in their own class to begin with, so you don’t have to change it later.
  • You can put your constants in an existing protocol, but it is often frowned upon to just use a protocol to store constants.

* Be careful with constants in their own classes: If you later change the class containing your constants and you don't recompile the other classes that reference that class, you will end up with both old and new values in your program.

Another thing to look out for is if you have a class with a constant you can declare and initialize a constant with the same name in a subclass, creating a new memory location with its own value. This is called shadowing, and results in 2 constants with the same name but with potentially two different values. You can prevent other people from shadowing your constants in a subclass by declaring the superclass final.

The console application below demonstrates the basic use of constants:


public class PressureCalculator 
{

	public static final double IDEAL_GAS_CONSTANT = 8.314472;
		
	public static void main(String[] args) 
	{
		System.out.println("Pressure = " + calculatePressure(5.0, 300.0, 1.0));
		System.out.println("Temperature = " +calculateTemperature(12471.708, 1.0, 5.0));
				
		/* 
		 * You reference a constant in another class by the 
		 * class name same as a static variable:
		 */
		System.out.println("Constants.SOME_CONSTANT_ONE = "
				+ Constants.SOME_CONSTANT_ONE);
		System.out.println("Constants.SOME_CONSTANT_TWO = "
				+ Constants.SOME_CONSTANT_TWO);
		
	}
	
	public static double calculatePressure(double numberOfMoles,
			double temperatureKelvin, double volumeLiters)
	{
		//Pressure = nRT / V
		double pressurePascals = 
			(numberOfMoles * IDEAL_GAS_CONSTANT * temperatureKelvin )
			/ volumeLiters;
		
		return pressurePascals;
	}
	
	public static double calculateTemperature(double pressurePascals,
			double volumeLiters, double numberOfMoles)
	{
		//Temperature = PV / nR
		double temperatureKelvin = 
			(pressurePascals * volumeLiters ) 
			/ (numberOfMoles * IDEAL_GAS_CONSTANT );
		
		return temperatureKelvin;
	}
}

Here is our class that hold our constants:


/* 
 * a constant can be shadowed, thus changed in a sub-class,
 * so declaring your constant containing class final will
 * prevent this. 
 */

public final class Constants 
{
	public static final double SOME_CONSTANT_ONE = 1.1;
	public static final double SOME_CONSTANT_TWO = 2.2;
}

15Apr/110

Java Article 23: Static Fields

The term static in Java can be confusing so in this article I will try to clarify it as much as possible, or at least provide a new perspective on the topic. The term static can apply to fields, methods, and initialization blocks but in this article we are just talking about static fields. I will talk about the others in subsequent articles.

I think when most new programmers think of a variable in Java they think of something like:

public class someClass
{
int myInt;
}

This is an example of an instance variable. myInt is meant to be used by an object and cannot be used by a class that is not instantiated.

A static field is a variable that is associated with a class and it is a single location in memory shared between subclasess and instances (objects) of this class.

Below are a couple of examples of static fields:

public class someOtherClass
{
private static int someInt;
public static String someString = “this is just some string’;
}

Static fields have the modifier “static” included as shown. The static modifier tells you (and the compiler) that these variables are static fields and not instance variables.

Static fields were created to provide a variable that works differently from instance variables. An instance variable only exits in one particular object and can only be referenced from an object. Here, referenced means used by, changed, or to retrieve the value of, etc. An instance variable can not be referenced from a class.

A common IDE error message new programmers see in Java is “Cannot make a static reference to the non-static field.” You get this error when you try to reference an instance variable from a class (a stand-alone class that in not instantiated into an object).

So all this means is that static fields do not require any objects to exist for the static fields to be referenced. So with static fields you can write and use classes that never get instantiated into objects. One use of a class with static fields (and static methods which we will talk abut in the next article) would be a class that does a calculation and returns a value. You do not need an object to do this and you save a little memory and a few lines of code by not instantiating an object.

The above could take the form of:


public class ClassA 
{
	public static void main(String[] args) 
	{
		ClassA classAObject = new ClassA();
	}
	
	public ClassA()
	{
		//Since we are calling a class and not an object
		//we have to use the Class's name: ClassB
		System.out.println(ClassB.multiplyTwoValues(2,3));
	}
}

...then our class with the static method


public class ClassB 
{
	public static float multiplyTwoValues(float firstNumber, 
             float secondNumber)
	{
		//local variable
		float returnValue = firstNumber * secondNumber;
		return returnValue;
	}	
}

Ok all that is great, but maybe you are reading this article because you were already a bit uncomfortable with the term static, and the whole static concept (or perhaps you are stuck waiting at the dentist’s office and you don’t want to read a Highlights magazine from 1974.)

To me there are several things about static fields that are immediately confusing:

In Java, the term static field has several synonyms. Static fields can also be called:

  • fields
  • class fields
  • static variables
  • class variables

You can probably get away with calling them any of the above without sounding dumb. I prefer to keep the word static or class in there to remind people the variable applies to the class. I also like the world variable over field since it uses the same naming scheme as other variables (e.g. instance variables and methods variables).

The term static is also misleading:

In English, the word static typically is thought to mean “lacking in change, being fixed, or immobile.” Programming language architects have come up with some great usages of English words in programming but this is not one of the best.

The value of a static field can be changed. In fact, both objects and classes can reference and change static fields. One cool thing about static fields is that they are easily referenced/changed by classes and objects.

I tend to think of the modifier static as meaning “it is a single fixed memory location that is held there for widespread use.”

It is a bit like a dry-erase board in the front of a classroom. If the instructor or any student make a change to it, all other students in that class now have the new value for dryEraseBoad. dryEraseBoad is one variable that is shared by all members of the class.

On the other hand, an instance variable is like a student’s notebook. Individual notebooks are owned by each of the students and what a student writes in their individual notebook is unique to that particular notebook and does not impact any of the other notebooks.

So in today’s example there is a main class that acts on a superclass and a subclass. The super and subclasses both manipulate a class variable (also know as the field or static field) and an instance variable. You can see they all share the same value for the class variable and then each have their own value for the instance variable.


public class MainClass 
{
	//this is just here to show we can't reference it from the static method:
        int myInt; 
		
	public static void main(String[] args) 
	{
		//Note: you can't reference an instance variable from a class:
		//TheSuperClass.objectName = "";
		//nor can you reference the above instance variable:
		//myInt = 5;
		
		System.out.println("Note: Even before the object is " +
				"instantiated we can reference " +
				"\nour static " +
				"field, aClassVariable:");
		System.out.println("aClassVariable = " 
				+ TheSuperClass.aClassVariable);
		
		TheSuperClass superClassObject 
		= new TheSuperClass("superClassObject");
		
		TheSubClass subClassObject1 
		= new TheSubClass("subClassObject1");
		
		TheSubClass subClassObject2 
		= new TheSubClass("subClassObject2");
		superClassObject.displayTheClassVariable();
		superClassObject.displayTheInstanceVariable();
			
		//now we can access the variables
		//Class variables should be referenced by the class name
		System.out.println("\nNote: Every instance of TheSuperClass" +
				" and its subclasses" +
				"\nshare our class variable, which is in " +
				"one fixed location in memory:");
		System.out.println("TheSuperClass.aClassVariable = " 
				+ TheSuperClass.aClassVariable);
		System.out.println("TheSubClass.aClassVariable = " 
				+ TheSubClass.aClassVariable);
	}
}

Then our super class


public class TheSuperClass 
{	
	public static String aClassVariable = "This is the static " +
			"field declared in the superclass"; 
	
	public String aInstanceVariable = "This is the " +
	"string declared in the superclass"; 
	
	String objectName;
	
        //constructor	
	public TheSuperClass(String name) 
	{
		this.objectName = name;
		System.out.println("\n" + objectName + " has been created");		
	}
	
	public void displayTheClassVariable()
	{
		System.out.println("\n" + objectName 
			+ ": aClassVariable = " + aClassVariable);
	}

	public void displayTheInstanceVariable() 
	{
		System.out.println(objectName 
			+ ": aInstanceVariable = " + aInstanceVariable);
		
	}
}

Then finally we have our subclass



public class TheSubClass extends TheSuperClass
{
	public TheSubClass(String name)
	{
		super(name);
		
		System.out.println(objectName + ": aClassVariable = " 
				+ aClassVariable);
		System.out.println(objectName + ": is now " +
				"modifying aClassVariable...");
		
		aClassVariable = aClassVariable + " (modified by " 
		+ objectName + ")";
		System.out.println(objectName + ": aClassVariable = " 
				+ aClassVariable);
		
		//now we modify aInstanceVariable
		System.out.println("\n" + objectName 
				+ ": aInstanceVariable = " 
				+ aInstanceVariable);
		System.out.println(objectName 
				+ ": is now modifying " +
						"aInstanceVariable...");
		aInstanceVariable = aInstanceVariable 
		+ " (modified by " + objectName + ")";
		System.out.println(objectName + ": aInstanceVariable = " 
				+ aInstanceVariable);
		
	}
}

Another use for static variables is to create constants, which I will cover in the next article.

8Apr/110

Java Article 22: Java Collections – HashMap

HashMaps are another variety of container (collection) object. They differ from other commonly used Java collection objects such as Arrays, ArrayLists, and LinkedLists in that they don’t have indexes and their elements are not sorted. HashMaps implement the Map interface and not the List interface. HashMaps store their elements by a key. This is referred to as a key-value pair since the collection contains a key that is associated with a value (one of its elements).

Performance-wise HashMaps are very fast and are good for tasks such as looking up X if you know Y. I like to think of them as unordered lookup tables (the old-fashioned ones in an engineering reference book used to quickly find a density at a given temperature or enthalpy).

HashMaps are instantiated as other collection objects, but both the key and value types should be specified:

HashMap <String, String> products = HashMap <String, String> ();

You can also pass initial capacity and load factor as parameters which can be used to adjust memory and processor usage:

HashMap(int initialCapacity, float loadFactor)

You don't have to worry about too much about this for simple programs. Just remember the option is there if someday you need to optimize performance. The default load factor (no arguments) provides a balanced solution.

Also you can pass another Map object to create a new map with the same mappings:

HashMap(Map myMap)

So in business application you could have a product number as a key and the product name as the value. Strings are often used but another interesting application would be to use a string as a key and an object containing a variety of other data as a value.

Key-value pairs are added to HashMaps similar to other container objects except that instead of add(), the put() method is used, and both the key and value are passed as arguments:

//product number and product name
products.put(“1111”, “low quality ham”);

products.get(“1111”);

will return the product name associated with key 1111.

Today’s program demonstrate some of HashMap’s methods:


import java.util.*;

public class HashMapExample 
{

	static HashMap <String, String> products = 
		new HashMap <String, String> ();
		
	public static void main(String[] argv)
	{
		
		demonstratePut();
		demonstrateView();
		demonstrateIterate();
		demonstrateContains();
		demonstrateRemove();
		
	}


	private static void demonstratePut() 
	{
		
		System.out.print("Here we add some key-value pairs to " +
				"our HashMap with put():");
		
		products.put("1111a", "Low Quality Ham");
		products.put("1112f", "Medium Quality Ham");
		products.put("1113m", "High Quality Ham");
		products.put("1114z", "Radioactive Ham");
		displayCollection();
		System.out.print("\nNotice they are not in the " +
				"same order added");
		
	}
	
	
	
	private static void displayCollection() 
	{
		//The contents of many collection objects can be 
		//printed simply by:
		System.out.print("\nproducts contents: " + products);
		
	}
	
	private static void demonstrateView() 
	{
		System.out.println("\n\nOther ways of viewing key " +
				"& values:");
		System.out.println("entrySet(): " + products.entrySet());
		System.out.println("keySet(): " + products.keySet());
		System.out.println("values(): " + products.values());
		System.out.println("get(\"1111a\"): " 
				+ products.get("1111a"));
		System.out.println("get() will return null if the " +
				"key-value pair is not present:");
		System.out.println("get(\"XXXX\"): " 
				+ products.get("XXXX"));
		
	}
	
	/*
	 * While not as straightforward as other collection classes
	 * you can still iterate though a HashMap:
	 */
	private static void demonstrateIterate() 
	{
		
		System.out.println("\nIteration examples: ");
		//using for-each and keySet()
		for (String key : products.keySet())
		{
			System.out.println(key);
		}
		System.out.println();
		//using for-each and Map.Entry
		for (Map.Entry e : products.entrySet())
		{
		    System.out.println(e.getKey() + ": " + e.getValue());
		}
	}
	
	private static void demonstrateContains() 
	{
		System.out.println("\nTesting for keys and values:");
		System.out.println("containsKey(\"1111a\"): " 
				+ products.containsKey("1111a"));
		
		System.out.println("containsValue(\"Radioactive Ham\"): " 
				+ products.containsValue("Radioactive Ham"));
		
	}

	private static void demonstrateRemove() 
	{
		System.out.println("\nproducts.remove(\"1114z\") removes " +
				"this key. The value is then inacesseable:");
		
		products.remove("1114z");
		displayCollection();
		
	}






	
}

General Notes:

  • HashMaps do not allow for duplicate keys. So if you use put() with the key again, the value will be overwritten.
  • If you need a collection kept in order use a TreeMap. There are also LinkedHashMaps.
  • HashMap only works with objects with a suitable hashCode() implementation, and TreeMap only works with Comparable objects.

I try to point out confusing terminology when I come across it and the word collection is one of those words that can mean a number of things in Java:

  • A collection, in general computer science terms, is an object that serves as a container for other data. It is a data structure.
  • Java refers to its collection objects as the Java Collections Framework.
  • “Collection” is an interface implemented by some, but not all of the classes in the collections framework.
  • “Collections” is a class in Java with methods for manipulating collections (container objects).

So a HashMap is collection object that does not implement the Collection interface but it is part of the Java Collections Framework.

Simple right? Yes, I know it not all that simple. The more you use and read about all this the more clear it will all become.

1Apr/110

Java Article 21: Java Collections – LinkedList

Another kind of container object useful for holding an ordered collection of objects is the LinkedList. The LinkedList is a close relative of ArrayList which we covered in our previous article. Both classes implement the List interface (among others) and by convention share the word List in the latter part of their name.

LinkedLists don’t use arrays like ArrayLists. In a LinkedList each element has a pointer to the element before it and to the element following it. Because of this LinkedLists and ArrayLists will perform differently from processing time and memory usage standpoints.

I am not going to get into all the differences in performance here except to say a LinkedList can add elements very quickly to its beginning or middle, and there is no capacity to manage. Ultimately performance really depends on what you are doing with your collection. When performance is a concern you are best off testing each side by side and seeing which is better for your particular application.

Often LinkedLists are selected for use because of the methods in this class. LinkedList has most of the common methods ArrayList has (add(), get(), set(), remove(), size(), etc) plus a number of new methods that can be very convenient:

addFirst(object) & addLast(object): adds the object to the beginning or end of the LinkedList.

peek(): This just returns the first element of the LinkedList. Appreciate this method name: The language architect here seemed to be feeling cutesy, which you don't see often.

poll():This returns and removes the first element of the LinkedList. Also this will return null if the LinkedListis empty.

offer(): Attempts to add object to the end of the LinkedLists, and returns a Boolean based on weather it was added or not.

removeFirst() & removeLast(): Returns and removes the last element.

Here is a quick program showing LinkedList in action:


import java.util.LinkedList;


public class LinkedListExample 
{

	static LinkedList <String> myLinkedList = 
		new LinkedList <String> ();
		
			public static void main(String[] argv)
	{
		
		demonstrateAddFirstAndLast();
		demonstratePeek();
		demonstratePoll();
		demonstrateOffer();
		demonstrateRemoveFirstAndLast();
		demonstratePollWithEmptyList();
	}


	


	private static void demonstrateAddFirstAndLast() 
	{
		
		System.out.print("Here we add some elements to the" +
			" beginning of our LinkedList with addFist():");
		
		myLinkedList.addFirst("Object A");
		displayCollection();
		myLinkedList.addFirst("Object B");
		displayCollection();
		myLinkedList.addFirst("Object C");
		displayCollection();
		myLinkedList.addFirst("Object D");
		displayCollection();
		
		System.out.print("\nHere we add Object E to the" +
		" end of our LinkedList with addLast():");
		myLinkedList.addLast("Object E");
		displayCollection();
		
		
	}
	
	private static void demonstratePoll() 
	{
		System.out.println("\nHere we see how poll() works:");
		System.out.println("The first element in the list is: " 
				+ myLinkedList.poll());
		System.out.print("poll() also removes the element:"); 
		displayCollection();
		
	}
	
	private static void demonstratePeek() 
	{
		System.out.println("\nHere we see how peek() works:");
		System.out.println("The first item in the list is: " 
				+ myLinkedList.peek());
		
	}

	private static void demonstrateOffer() 
	{
		// TODO Auto-generated method stub
		System.out.println("\nHere we see how offer() works:");
		//offer() will return true if the object was added
		System.out.println("ObjectFromOffer was sucessfully " 
				+ "added to the end: " 
				+ myLinkedList.offer("ObjectFromOffer"));
		displayCollection();
	}
	
	private static void demonstrateRemoveFirstAndLast() 
	{
		System.out.print("\nFinally, we will remove the " +
				"first element with removeFirst():");
		myLinkedList.removeFirst();
		displayCollection();
		System.out.print("\n...and removeLast(): ");
		myLinkedList.removeLast();
		displayCollection();
		
	}
	
	private static void displayCollection() 
	{
		//String whatWeAreDoingNow
		System.out.println("\nCollection Contents:");
					
		for (String stings : myLinkedList)
		{
			
			System.out.println(stings);
		}
	}
	
	private static void demonstratePollWithEmptyList() 
	{
		
		myLinkedList.clear();
		
		System.out.println("\nHere we clear the list to show" +
				" how poll() works with an empty list:");
		System.out.println("The first element in the list is: " 
				+ myLinkedList.poll());
		
		//With this, you can also do:
		if (myLinkedList.poll() == null)
		{
			System.out.print("Empty");
			//do something if its empty
		}
		
		if (myLinkedList.poll() != null)
		{
			System.out.print("not Empty");
			//do something if its not empty
		}

		
	}
		
}

25Mar/110

Java Article 20: Java Collections – ArrayList

ArrayLists are another kind of container object useful for holding an ordered collection of objects. ArrayLists work similar to arrays in that values can be inserted, accessed, or removed from specific elements by index. If you are not familiar with arrays you should look at our previous article so you know what we are talking about when we mention things like elements and indexes.

Unlike arrays ArrayLists are resizable which makes them very useful for holding objects created during runtime, where the exact number of objects to be created depends on the user’s actions and is unknown to the programmer. ArrayLists cannot hold primitive types unless the primitive is contained in a special wrapper class.

Wrapper class is a bit of a strange sounding term to some, but they “wrap” a value of a primitive type in an object. There is a wrapper class for each primitive type and you can identify them because they begin with an upper case letter indicating that they are classes (e.g. Integer is the wrapper class for int, Double for double.)

Wrapper classes have many handy methods, and are commonly used to covert a primitive type to a string:

int myInteger = 4;

String myString = Integer.toString(myInteger);

They are also needed when working with Swing components since many of them deal with text:

float someFloat = Float.parseFloat(myTextField.getText());

Parse is another uncommon English word you will see. Above, it is converting a string from a TextField to a float. The term parse is fitting since it means to analyze, resolve or dissect into parts, or to describe.

While arrays have a fixed size (its length property) that is specified at instantiation, ArrayLists lists have both a capacity and a size. The size of the ArrayLists is the number of actual values contained within the ArrayList. Capacity relates to the amount of memory set aside to hold the elements of the ArrayList, and it is always at least as large as the list size. As elements are added to an ArrayList, its capacity is increased automatically.

An ArrayList uses an array to store its elements. If the ArrayList needs to grow it creates a new array and copies all of its values to the new array. There is no way provided by the API to get the value of an ArrayList’s capacity, but you can set it and adjust it. Capacity is typically not something new java programmers have to worry a lot about, however how you set and adjust capacity can, in more extreme cases, impact system performance/resources.

ArrayLists are objects and are instantiated in a similar way:

ArrayList <String> myArrayList = new ArrayList <String> ();

The angle brackets are something you may not have encountered before, and they indicate that the ArrayList object is restricted to a particular type of object. In the above example we specify that the ArrayList will hold only string objects. These angle bracket casts are referred to as generics. This is called a parameterized type: ArrayList <String>.

It is possible to omit the generics, allowing your ArrayList to hold any object type, but this is generally not considered good practice (by type safety advocates) since it goes against the principles of type safety and having a strongly typed language. Your Java compiler should give you a warning if you don’t include the generics. This is another form of mistake proofing (poka yoke). Some languages are less strongly typed and people argue about what extent of type safety is best.

An example of what could happen if you did not use generics is if you had an ArrayList:

ArrayList myArrayList = new ArrayList (); //I intend to fill this full of Integer objects
//the above is called a raw type since it has no parameterized type (no <Integer> in this case);

myArrayList.add(Integer.valueOf(4));
myArrayList.add(Integer.valueOf(4));
//programming error now throws a wrench into the system:
myArrayList.add(String.valueOf(5));
int x = 0;

for (int i = 0; i < myArrayList.size(); i++)
{
x += ((Integer) myArrayList.get(i)).intValue();
}

System.out.println(x);

When the for loop gets to the string object it would generate a ClassCastException and crash since you can’t cast a string to an int. This kind of problem is more likely in a team environment where you wrote the for loop and other programmers are now sending various objects to your for loop. One programmer sending one wrong object type to your for loop will likewise cause the same exception and a bug that needs to be tracked down between multiple programmers.

ArrayLists have some very cool methods, which I will illustrate in the program below:

import java.util.ArrayList;
import java.util.Arrays;


public class SimpleArrayList 
{

//constructs an empty ArrayList:
static ArrayList <String> firstArrayList = 
	new ArrayList <String> ();

//constructs an empty ArrayList, with an initial capacity of 10:
static ArrayList <String> secondArrayList = 
	new ArrayList <String> (10);

//constructs an ArrayList, and fills 
//it with the contents of secondArrayList:
static ArrayList <String> thirdArrayList = 
	new ArrayList <String> (secondArrayList);
	
	public static void main(String[] argv)
	{
		
		//shows the size of the ArrayList:
		showSize("Initial ArrayList size:");
		//add some items to our ArrayList:
		addToArrayList();
		showSize("\nSize after addToArrayList():");
		//Remove some items to our ArrayList:
		removeValuesFromArrayList();
		modifyArray();//change an element
		otherMethods();//Other methods of the ArrayList class
	}


	private static void showSize(String whatWeAreDoingNow) 
	{
		System.out.println(whatWeAreDoingNow);
		System.out.println("firstArrayList.size() = " 
				+ firstArrayList.size() + "\n");
		
	}


	private static void addToArrayList() 
	{
		//You can simply add items to the end of the ArrayList:
		firstArrayList.add("Object A");
		firstArrayList.add("Object B");
		firstArrayList.add("Object C");
		//The ArrayList fills left to right.
		//you can also add an object to a specified index
		//firstArrayList.ensureCapacity(10);
		firstArrayList.add(3,"Object D");
		/*
		 * Adding an object to an occupied element moves
		 * all the other objects toward the end of the list 
		 */
		firstArrayList.add(0,"Object A-1");
		
		displayArrayList("\naddToArrayList(): Added some " +
				"objects to firstArrayList:");
	}

	private static void removeValuesFromArrayList() 
	{
		//You can remove items from ArrayList 
		//by the object's identifier:
		firstArrayList.remove("Object A-1");
		displayArrayList("removeValuesFromArrayList(): " +
				"we removed Object A-1\n " +
				"and the objects " +
				"are moved toward the beginning of the list" +
				" when one is removed:");
		
		//...or removed by index
		firstArrayList.remove(2);
				
		displayArrayList("\nremoveValuesFromArrayList(): " +
				"we removed the oject at index 2:");
	}

	private static void displayArrayList(String whatWeAreDoingNow) 
	{
		
		System.out.println(whatWeAreDoingNow); 
		//This is an advanced for loop also called a forEach loop:
		for (String stings : firstArrayList)
		{
			/*
			 * Read the above as "execute this for each 
			 * String object, strings, from firstArrayList"
			 */
			System.out.println(stings);
		}
	}
	
	private static void modifyArray() 
	{
		//Replaces an object to an index:  	
		//firstArrayList.set(index, object)
		firstArrayList.set(0, "A string added to index 0");
		/*
		 * There has to be an existing element here or you will
		 *  get an IndexOutOfBoundsException
		 */
		
		displayArrayList("\nmodifyArray(): " +
				"ArrayList after using " +
				"firstArrayList.set(0, " +
				"\"A string added to index 0\"):");
	}
	
	//Other cool methods 
	//(these are not all the methods available to ArrayLists)
	private static void otherMethods() 
	{
		
		//checks the ArrayList to see if it contains an object
		if (firstArrayList.contains("Object B"))
			System.out.println("\nfirstArrayList.contains"
					+ "(\"Object B\") = " 
					+ firstArrayList.contains("Object B"));
		
		//returns the index of an object
		System.out.println("\nIndex of the first occurance " +
				"of \"Object B\" = " 
				+ firstArrayList.indexOf("Object B"));
		/*
		 * ArrayLists may hold multiple objects with the same
		 * name (object identifier)
		 */
		
		//get an object from a particular index
		System.out.println("\nfirstArrayList.get(1) = " 
				+ firstArrayList.get(1));
		
		//We create a new array for use below:
		String[] anArray = new String[firstArrayList.size()];
		
		//Returns an array containing all of the elements in
		//firstArrayList:
		firstArrayList.toArray(anArray);

		
		System.out.println("\nWe created a new array, anArray," +
				" then we used firstArrayList.toArray(anArray);");
		
		System.out.println("to return the elements of " +
				"firstArrayList to anArray. " +
				"Here are the contents of anArray:");
		for (String stings : anArray)
		{
			System.out.println(stings);
		}
		
		System.out.println("\nHere clear all elements from" +
				" firstArrayList");
		//clears an ArrayList of all its elements:
		firstArrayList.clear();
		displayArrayList("after firstArrayList.clear(); " +
				"firstArrayList now has " 
				+ firstArrayList.size() + " values.");
				
		/*
		 * Now we can assign the items from anArray back to
		 * firstArrayList 
		 */
		firstArrayList = new ArrayList<String>(Arrays.asList(anArray));
		displayArrayList("\nAfter we assigned the contents of " +
				"anArray back to firstArrayList, it now has " 
				+ firstArrayList.size() + " values:");
	}
}

18Mar/110

Java Article 19: Intro to Java Collections – Arrays

Arrays are one of the many varieties of collections in Java. A collection is an object that serves as a container for other data. Put another way container objects group multiple values into a single unit (the container object). This single container object can then be manipulated, passed to a method, or acted upon within a loop.

One very cool thing about arrays and the other collections is that they hold objects (technically values that reference the objects). So if you were designing a card game you might put your individual card objects into some kind of collection and then you could do things like copy, search, sort or even randomize the collection of card objects with minimal effort.

It is right about here the terminology in involved with the Collections Framework can get pretty confusing to new programmers. Aside from arrays, the collection classes that you can use as containers are referred to as implementations. There are different categories of implementations, which I am not going to cover here. Different implementations have different interfaces. There are over a dozen interfaces which support the many implementations, and even custom implementations you can create yourself.

Like other classes the collection implementations have methods (algorithms) that can perform various tasks like sorting and searching. The methods a collection class can use depend on the interfaces it implements, just like with other classes you have encountered.

Confused? You should be. Don’t worry too much about all the implementation and protocol stuff for now. Just remember there are a lot of different container classes, and each one is useful for storing and manipulating data in a particular way. I will cover some of the more popular implementations in other articles since here we are going to discuss arrays.

While an array is conceptually a collection (an object that holds multiple values), and the Java API states it is part of the Collections Framework, the API also segregates it as one of the old collections that predate the modern new and shiny core collections. It does not implement any of the collection interfaces and it has its own methods. Because of this it is also a bit easier to use, and easier to understand, so it is usually the first collection or container object taught in a Java course.

Another thing that is different about arrays is that they can hold the primitive types (int, double, boolean etc) without special treatment (using a wrapper class).

Arrays are declared like other variables…

int[] myArrayOfInts;

…except for the empty brackets which indicate that this is an array (a single dimensional array).

Since arrays are objects you also have to instantiate them after you declare them:

myArrayOfInts = new int[10];

The “[10]” indicates the length of the array, also referred to as its number of elements. One disadvantage to using arrays is that their length is fixed and cannot be changed. So myArrayOfInts can hold 0 to 10 int values in its 10 elements.

Individual values are added to arrays by specifying the element’s index ([0], which has to be an int) and then the value to add to that element:

myArrayOfInts [0] = 12;

Above we add the int 12 to index 0. Index 0 if the first element in an array.

Elements of an array that are not assigned values will have the default empty value for the type: (e.g. numeric types will be 0, Booleans will be false, and objects (including strings) will be “null”; These empty values are inserted when the array is instantiated, then overwritten when you assign values.

As with other objects you can also declare and instantiate your array all in one line. The following diagrams show this and summarize what we discussed.

Then if we were to add three strings to the array…

myArrayOfNames [0] = “Bob”;
myArrayOfNames [1] = “Tom”;
myArrayOfNames [2] = “Joe”;

...we would have an array object that looked like this:

The array is one object as shown by the yellow box, the cups are elements, each element has an index that identifies it, and each element holds a value.

As a bit of a shortcut, you can also declare and instantiate an array as follows:

String [] myArrayOfLetters = {"A","B", "C"};

To retrieve an element from an array we simply use:

System.out.println(myArrayOfLetters [0]);

Or to assign it to an existing variable:

x = myArrayOfLetters [0];

One pitfall when working with arrays is when you try to reference an element that is outside of the bounds of an array:

System.out.println(myArrayOfLetters [3]); // ArrayIndexOutOfBoundsException

This can be a little confusing: while the length is 3, the 3rd index is actually the 4th element, since the index starts counting at 0.

So this program sums up the basics above:


/*
 * this library is only needed for the methods in otherMethods()
 */
import java.util.Arrays;

public class ArrayBasics 
{
	static String [] myArrayOfLetters = {"A","B", "C"};
	
	public static void main(String[] argv)
	{

		//shows the length of the array:
		System.out.println("myArrayOfLetters.length = " 
				+ myArrayOfLetters.length + "\n");
				
		displayArray();//print our array
		modifyArray();//change the 1st element
		displayArray();//print our array again to see the change
		otherMethods();//Other methods of the Array class
	}

	

	private static void displayArray() 
	{
		System.out.println(myArrayOfLetters[0]);
		System.out.println(myArrayOfLetters[1]);
		System.out.println(myArrayOfLetters[2] + "\n");
		
		/*
		 * Imagine how much typing would you have to do if your 
		 * array had 1000 elements. Therefore you should do
		 * this in a loop. See the next program when you are 
		 * done here.
		 */
		 
	}
	
	private static void modifyArray() 
	{
		myArrayOfLetters[0] = "some New Letter";
	}
	
	private static void otherMethods() 
	{
		System.out.println("Here are some other methods " +
				"of the Array class:");
				
		//Add a value to all elements of an array:
		System.out.println("Add a value to all elements " +
				"of an array:");
		Arrays.fill(myArrayOfLetters, "X");
		displayArray();
		
		//Add a value to a range of elements of an array:
		System.out.println("Add a value to a range of " +
				"elements of an array:");
		Arrays.fill(myArrayOfLetters, 0, 2, "Z");
		displayArray();
		
		//Sort the array in ascending order:
		System.out.println("Sort the array in ascending order:");
		Arrays.sort(myArrayOfLetters);
		displayArray();
		
		//Return the index for the specified value in the array:
		System.out.println("X is at index " 
				+ Arrays.binarySearch(myArrayOfLetters, "X"));
		
		//Copy an array to a new array:
		String[] copyOfMyArrayOfLetters 
		= Arrays.copyOf(myArrayOfLetters, myArrayOfLetters.length);
		//There is also copyOfRange to copy just part of an array.
	}
}

The real power of arrays are that they can be used with loops. We can do interesting things with arrays and loops that save us a huge amount of time as can be seen in the following program:



public class ArrayInALoop
{
	static int [] arrayOfInts = new int[10];
		
	public static void main(String[] argv)
	{
		fillArrayOfInts();
		displayArrayOfInts();
		modifyArrayContents();
		displayArrayOfInts();
	}

	
	private static void fillArrayOfInts() 
	{
		/*
		 * Weather our array has 10 or 10,000 elements this 
		 * will fill it with sequential numbers:
		 */
		for (int i=0; i < arrayOfInts.length; i++)
		{
			arrayOfInts[i] = i;
		}
		
	}

	private static void displayArrayOfInts() 
	{
		/*
		 * Then here we can easily print them all:
		 */
		for (int i=0; i < arrayOfInts.length; i++)
		{
			//System.out.println(arrayOfInts[i]);
			System.out.println(arrayOfInts[i]);
		}
		System.out.println("\n");
	}
	
	private static void modifyArrayContents() 
	{
		/*
		 * Then here we can easily modify the values 
		 * contained within the array:
		 */
		for (int i=0; i < arrayOfInts.length; i++)
		{
			//multiply the value in each element by 2:
			arrayOfInts[i] *= 2; 
			/*
			 * Imagine what a pain it would be doing this to
			 * a very long array without using a loop.
			 */
		}
	}
}

You can also have an array of arrays, called a two-dimensional array, or even multidimensional arrays. These follow the same syntax but have additional sets of brackets per dimension:

type[] [] arrayName = new type [X elements] [Y elements];

11Mar/110

Java Article 18: Objects in an ArrayList & Examples of Enterprise Software used in Manufacturing

Rather than just working in the software industry, many hatchling programmers will go on to work in roles that support business and manufacturing operations.

Aside from the standard office productivity software like word processors and spreadsheets we all have seen or heard of from an early age, and all the software supporting networks and servers, there are a slew of other software packages used in business. These systems are being implemented with increasing frequency, serving an almost ridiculous variety of business needs available in off-the-shelf, modular, and custom software packages.

The term Enterprise Software is just a fancy term for Business software, however it can also refer to a business software package that serves a company-wide need verses a just a departmental need (like A CAD just being used in an engineering department).

One company I worked for had a software package dedicated to managing employee’s developmental goals. So each year every employee would have to enter items that they needed to complete to develop themselves so they can do their jobs better. You might enter that you want to attended certain courses or seminars or have the company buy some periodicals or other literature for you to “continuously improve” yourself.

While I was rather impressed the company valued us so, and investing in employees is important to me, this did add extra work to everyone’s already busy schedule. Managers had to review what was entered, approve or reject it, facilitate the plan, then at the end of the year ensure the plan was satisfied. Middle management was involved as well. Looking at the amount of labor involved made me question the design of the system.

One symptom of employee pushback is when you start seeing plans such as “I need to develop my ability to come up with better developmental goals.”

Well enough with the anecdotes… A few common enterprise system examples that come to mind are:

Enterprise Resource Planning systems (ERP): These systems often consist of several modules including apps for production, human resources, accounting, sales, and more. They also tie together all the modules so someone in marketing can look at production volumes, product reject rates, or the status of a particular lot of product. This system is also of great interest to accounting groups since the can easily access dollar values for things like raw materials purchased and used, and product units manufactured and sold. These can also interface with web applications like an online retail store.

ERP systems for larger companies can cost from a few hundred thousand to tens of millions of dollars depending on the size of the company and what the system is designed to do. This is the total cost of ownership (TCO) which includes all the hardware, facilities, software, various support services, and in-house staff costs needed for the software. These systems can be painful to implement: It completely shut down production in one facility I worked at. This facility produced about 10 million dollars a week in revenue. Examples of ERP packages are SAP ERP and JD Edwards EnterpriseOne.

Another example would be Laboratory Information Management Systems (LIMS) which collect and manage data from various networked testing instruments providing for reviews, approvals, sample and data tracking, trending, supplemental documentation, and searching functions. Back in the 1900’s (the “old days”) people had to write all this data down in logbooks and then search though piles of logbooks or files of printed certificates to find the raw data and results later.

Another system common in manufacturing are Computerized Maintenance Management Systems (CMMS). Factories have equipment that needs various periodic checks, service, replacement, and calibration (maintenance). Maintenance tasks can be managed, assigned, documented, reviewed, tracked, trended, searched, and scheduled though these software packages. Maximo is a common CMMS.

In high-tech industries like the pharmaceutical industry a small building housing the manufacturing equipment for just one part of the overall process to produce just one drug can have thousands of instruments and equipment needing maintenance one or more times every year. (One of many reasons medicines are expensive).

I work a lot with production groups so today’s example will be a simple form that creates objects representing raw materials used in manufacturing. This would be just a small part of what would be included in an ERP. This module would be used mainly by supervisors and employees in receiving (they receive, document, and store incoming raw materials), quality control (test and release the raw materials) and on the production floor (convert the raw materials to product).

Raw materials are identified by their name, and a lot or batch number. There can also be other forms of identification like various inventory, part, vendor, and tracking numbers. Lot numbers (referred to as batch numbers for some product types like pharmaceuticals) are of particular interest since they can be used to trace the material back to the supplier’s manufacturing process or ERP system, and sometimes all the way back to the location where the martial was gown, synthesized, harvested, mined etc. Inspect a container of packaged food, a drug, or a box of gauze pads and you will see a lot number on it somewhere.

So below our example has two classes: a simple swing form MiniERP and a Lot class which is instantiated into individual lot objects which are then put into a ArrayList (more specifically a reference value to the object is put into the ArrayList). We then iterate though the ArrayList to view all the lots that were entered.

Here is MiniERP:


import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.Border;


public class MiniERP extends JFrame implements ActionListener
{
	Lot lot;
	ArrayList <Lot> lotList = new ArrayList <Lot> ();
	//Create a constant for a red border
	static final Border TEXT_BORDER = 
		BorderFactory.createLineBorder(Color.red);
	
	JLabel instructionsLabel = new JLabel("Add a few lots then" +
			" click \"Show Lots\"");
	JPanel panel = new JPanel();
	JLabel materialNameLabel = new JLabel("Material Name:");
	JLabel lotLabel = new JLabel("Lot Number:");
	JButton addLotButton = new JButton("Add Lot");
	static JTextField materialNameTextField =  new JTextField(10);
	static JTextField lotNumberTextField =  new JTextField(10);
	static JTextPane textPane = new JTextPane();
	JButton showLotsButton = new JButton("Show Lots");
	
	//Constructor
	public MiniERP()
	{
		panel.add(instructionsLabel);
		panel.add(materialNameLabel);
		panel.add(materialNameTextField);
		panel.add(lotLabel);
		panel.add(lotNumberTextField);
		panel.add(addLotButton);
		panel.add(textPane);
		
		JScrollPane scrollPane = new JScrollPane(textPane);
		scrollPane.setVerticalScrollBarPolicy
		(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setPreferredSize(new Dimension(200, 200));
		panel.add(scrollPane);
	
		panel.add(showLotsButton);
		addLotButton.setActionCommand("addLotClick");
		addLotButton.addActionListener(this);
		
		showLotsButton.setActionCommand("showLotsClick");
		showLotsButton.addActionListener(this);
		//Add the red borders:
		lotNumberTextField.setBorder(TEXT_BORDER);
		materialNameTextField.setBorder(TEXT_BORDER);
		textPane.setBorder(TEXT_BORDER);
	
		add(panel);
	}

	public void actionPerformed(ActionEvent e)
	{
		
		String cmd = e.getActionCommand();	
		
		if (cmd == "addLotClick")
		{
			lot = new Lot(materialNameTextField.getText(), 
					lotNumberTextField.getText());
			lotList.add(lot); //Add the lot to the ArrayList
			materialNameTextField.setText("");
			lotNumberTextField.setText("");
			materialNameTextField.requestFocus();
		}
		
		if (cmd == "showLotsClick")
		{
			String outputText = "";
		//Iterate though the ListArray and print out all the lots:
			for (int i =0; i < lotList.size(); ++i)
			{
				lot = lotList.get(i);
				outputText += i+1 + ". Material: " 
				+ lot.getName() + "\n" 
				+ "      Lot Number: " 
				+ lot.getLotNumber() + "\n";
				textPane.setText(outputText);
			}
			materialNameTextField.requestFocus();
		}
	}
	
	public static void main(String[] args)
	{
		MiniERP miniERP = new MiniERP();
		miniERP.setSize(250, 425);
		
		//this centers our window
		Dimension dimensions = 
			Toolkit.getDefaultToolkit().getScreenSize();
		int w = miniERP.getSize().width;
	    int h = miniERP.getSize().height;
	    int x = (dimensions.width-w)/2;
	    int y = (dimensions.height-h)/2;
	    miniERP.setLocation(x,y);
	    miniERP.setTitle("MiniERP");
	    miniERP.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    miniERP.setVisible(true);
	    materialNameTextField.requestFocus();
	}
}


And here is the Lot Class:


public class Lot 
{

	private String materialName;
	private String lotNumber;
	
	public Lot(String aName, String alotNumber)
	{
		materialName = aName;
		lotNumber = alotNumber;
	}
	
	//These are getter or accessor methods:
	public String getName()
	{
		return materialName;
	}
	
	public String getLotNumber()
	{
		return lotNumber;
	}
	
	
	
}

4Mar/111

Java Article 17: Passing References and Data Validation

In Article 16 we looked at naming swing components. Today I will show one way to use component names coupled with reference passing to save yourself some typing and make your program a bit more elegant. I am also going to touch a bit on data validation.

In computer science, data validation is the process of checking that data used by a program meets the specific requirements of that program (e.g. data type, minimum or maximum character lengths, or the presence or absence of certain characters).

A simple example would be a program that accepts a person’s name, like in a contact list, or in a program that manages a company’s customer information. One way the company can improve the accuracy and quality of their customer database would be to ensure that every customer entered into their database has a contact name included in the data input into the system. Also you would want to alert the user with an error message if they forgot to enter the customer name. This is one simple and classic example of validation.

We are going to simulate this situation with a swing interface class called PassReference which will pass a reference to one of its textfields to another class called CheckReference. CheckReference will then check (validate) that there is text present in this field before accepting the name. CheckReference will also display a message stating weather the data was accepted or not.

From an engineering standpoint this is a form of poka yoke, also referred to as mistake proofing, or the less politically correct term idiot proofing. If you were the sales manager responsible for this customer database you would not want entries in your system without customer names. Put another way, you want to ensure the people using the program are forced to include a name in the customer record.

We accomplish our data validation here by passing a reference to an object (our textfield) as an argument. In a method call passing a reference has the same syntax as passing a value:

This calls a method that receives the number 8 as a parameter and does something with it.

int myInt = 8;
doSomethingWithThisInt(myInt);

public void doSomethingWithThisInt(int myInt)
{
newNumber = myInt * 20;
}

Passing a reference to an object is done similarly:

JTextField textfield = new JTextField();
doSomethingWithThisObject(textfield);

public void doSomethingWithThisObject (JTextField textfield)
{
System.out.print(textfield.getClass())
textfield.setText("Hello!");
}

Once you have a reference to textfield you can then modify textField’s properties, like its text or background color, even from another class. This is a very powerful feature.

A lot can be said about passing references in Java… and I am not going to cover it all here. A few things to keep in mind are:

  • Java is officially a “pass by value” language. When you pass an object in Java, like a JTextField, you are not passing the actual object. You are also not passing a copy of the object. You are passing a value that represents a location in memory where the object is stored. In other languages this is called a pointer.
  • Passing references to objects is a powerful tool but bugs that include references can be difficult to resolve so some people recommend avoiding them in Java. In other languages like Objective-C object references (pointers) are the recommended practice and are used all the time. Contradictions like this tend to suggest there is no definitive answer as to weather use of references is a good or bad practice, so you need to determine what works best for you.
  • Things like references take some effort to understand. Don’t expect to read a couple of paragraphs about them and have a firm grasp of how they work and what they can be used for. You need to dive in and experiment with them.

Here is a simple example on how pass by value works with a primitive type like an int:


public class PassValue 
{
	static int myInt = 8;
	
	
	public static void main(String[] args)
	{
		doSomethingWithThisInt(myInt);
		System.out.println("Notice that after the call to " +
				"doSomethingWithThisInt, myInt has not changed: "
				+ myInt);
		System.out.println("This is because doSomethingWithThisInt()" +
				" is only working with a value, and not the memory" +
				" location named myInt");
		/*
		 * The value for myInt is not changed in the method below.
		 */
	
	}
	

	static public void doSomethingWithThisInt(int incommingInt)
	{
		System.out.println("Received value: " + incommingInt);
		incommingInt = 0; // we reassign incommingInt
		System.out.println("Reassigned value: " + incommingInt);
	}

}

Similar to primitive types, when you pass an object in Java, like a JTextField, you are not passing the actual object. You are also not passing a copy of the object. You are passing a value (remember Java is a pass by value language) that represents a location in memory where the object is stored. In other languages this is called a pointer, because it points to a location in memory. Put another way it is like an address to a house, not the actual house.

Passing a reference to an object can be seen in action along with data validation in today’s main example:

Here is the Main class that is the interface:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class PassReference extends JFrame implements ActionListener 
{
		JPanel panel = new JPanel();
		JTextArea labelOne = new JTextArea("Customer name:");
		JButton button1 = new JButton("Validate");
		static JTextField textField1 =  new JTextField(10);
		
		//Constructor
		public PassReference()
		{
			panel.add(labelOne);
			panel.add(textField1);
			panel.add(button1);
		
			button1.setActionCommand("button1Click");
			button1.addActionListener(this);
			//We name the textfield for use later
			textField1.setName("The Customer Name");
			
			add(panel);
		}

		public void actionPerformed(ActionEvent e)
		{
			
			String cmd = e.getActionCommand();	
			
			if (cmd == "button1Click")
			{
				CheckReference checkReference = new CheckReference();
				//here we pass a reference to textField1
				checkReference.checkTextField(textField1);
			}
		}
		
		public static void main(String[] args)
		{
			PassReference passReference = new PassReference();
			passReference.setSize(250, 100);
			
			//this centers our window
			Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize();
			int w = passReference.getSize().width;
		    int h = passReference.getSize().height;
		    int x = (dimensions.width-w)/2;
		    int y = (dimensions.height-h)/2;
		    passReference.setLocation(x,y);
		    
			passReference.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			passReference.setVisible(true);
			
			//This puts the cursor in the textfield
			textField1.requestFocus();
		}
}

Here is the second class (sometimes called a helper class in java) that does the data validation:



import java.awt.Color;

import javax.swing.*;

public class CheckReference 
{
	//We use allcaps to denote a constant
	final static int STRING_LENGTH = 0;
	/*
	 * A constant is a variable that we don't intend to change
	 * The keyword final prevents STRING_LENGTH from being changed
	 * Elsewhere in our program.
	 */
	
	public void checkTextField(JTextField incommingTextFieldReference)
	{
		
		/*
		 * Now that we have a reference to our JTextField object
		 * we can get all kinds of information about it
		 */
		System.out.println(incommingTextFieldReference);
		System.out.println(incommingTextFieldReference.getClass());
		
		//Here we get the current text length from the textfield
		if (incommingTextFieldReference.getText().length() 
				== STRING_LENGTH)
		{	
			/*
			 * here we use a JOptionPane to show a pop-up message
			 */
			JOptionPane.showMessageDialog(null, 
					incommingTextFieldReference.getName() 
					+  " must be > " + STRING_LENGTH 
					+ " characters.","Data Entry Error"
					,JOptionPane.WARNING_MESSAGE);
			
			/*
			 * Now that we have a pointer to textField1 we can 
			 * change its properties
			 */
			incommingTextFieldReference.setBackground(Color.red);
			incommingTextFieldReference.requestFocus();
		}

		else
		{
			/*
			 * You can do some fancy stuff with your message 
			 * dialogs using the reference to textfield1
			 */
			JOptionPane.showMessageDialog(null, 
					incommingTextFieldReference.getName()
					+": \""
					+ incommingTextFieldReference.getText()
					+ "\""
					+ " is validated and accepted",
					"Validation Complete"
					,JOptionPane.INFORMATION_MESSAGE);
			
			incommingTextFieldReference.setBackground(Color.white);
		}
		
	}
}

When you launch this application try leaving the text field blank and see what happens. Next add some text to the textfield and see how it is accepted by the checkReference object.