Wednesday, November 28, 2012

Dino Programmers Need Not Fear Java

While most of this blog focuses on assisting beginning programmers to learn Java as their first computer language, I also try to make it useful to those who are "old school" programmers, like myself, that want to make the transition to the newer language.

I was an accomplished programmer in many procedural and functional languages before I came to any of the Object-Oriented languages. In fact, my favorite language was Modula-2, which worked so well for me doing everything that OO languages were said to do, that I didn't make the transition to OO until about 1994 (a bit late in the game for those who were supposedly active in taking up new languages back then.)

Tools Getting in the Way of the Work
When I came to OO, I had a real hard time learning the whole OO "thing". Much of it looked no different than language structures that enforced normal coding practices used elsewhere. Other parts of it just looked like un-needed restrictions on data access. It was very frustrating.

Part of what slowed my transition to OO had nothing to do with the languages, however. The tools were new, too. That is, I was trying to do things as I was advised to by those more experienced than myself. Rather than using my usual technique of starting out with a text editor and command line compiler and linker, I allowed myself to be talked into going whole hog on IDE interfaces I wasn't familiar with. Once I was in them, I did get some information from them as I worked that helped a bit. But they kept me from really understanding the languages themselves for about a year longer (when nibbling at them part time outside my usual work) than it would have otherwise.

Welcome, Fellow Dinos!
When I started this blog, I strongly considered focusing it on other programmers like myself trying to get comfortable with the move from older languages and programming styles. By the time I did, I was actually pretty comfortable with several OO languages and many development environments and tool chains. But I could still feel the tug of Turbo Pascal when I got frustrated, or plain old vi and make with cc and a system-appropriate linker behind it.

In fact, I still do. There are a fair few nights I unwind by firing up my Ampro Little Board Z-80 system, which runs CP/M 2.2, and having at Turbo Pascal or ASM. Just for relaxation.

It's like embroidery or quilting for aging nerds, I guess.

Java for Dinos
I'm good with being called a dino, so I hope it doesn't put you off if you're an old-timer, too. (Am I really an old timer now? Some folks say so.)

Java is really awfully easy to use at the command line. Create a source file with your favorite text editor.* Open up a command line (no matter what OS you're on), cd to the directory where you saved the file, and compile it with:

Replace filename with your file's name, of course.
At this stage you need to include the .java file extension. It will produce a new file with the same name but a .class extension is on it now.

Once it completes successfully (and if it doesn't, and old timer should be able to read the error messages and line numbers to fix the code), use the following to run your program:
java filename

Note that even though you're running a .class file, you don't specify the file extension for the java runtime. You'll get an error that makes it look like there's something wrong with your file if you do:
>java Howdy.class
Exception in thread "main" java.lang.NoClassDefFoundError: Howdy/class
Caused by: java.lang.ClassNotFoundException: Howdy.class
 at Method)
 at java.lang.ClassLoader.loadClass(
 at sun.misc.Launcher$AppClassLoader.loadClass(
 at java.lang.ClassLoader.loadClass(

And, if you go to compile your program and get really, really long lists of errors, don't be discouraged. Remember the old maxim--fix the first error. Chances are most or all of the rest are errors that cascaded from the first one.

Why Bother?
Java will get you a lot of code that you'd have to write yourself otherwise. Now, this isn't unique to Java these days, it's become the norm for many languages. But you won't find yourself creating a socket driver or string handling routines. Plus, you can treat Java as either a procedural or functional language if that suits you. I did for the most part until about five years ago or so. I got a lot of work done with it, even at that.

But, I moved on to using Java "as it was meant to be" over time, because it meant rewriting less code, or less work re-using code. I just took getting there one step at a time. Learning how to do everything I did fluently in Modula-2, or LISP, in Java. (Or one of the various Pascals, or C, etc.) Libraries, general purpose re-usable code, flexible data structures, and so on.

Come In and Look Around
Have a look at my Basic Java Articles, listed in the right column. I strive to post actual working code in my examples, in the form of complete programs. So you don't have to guess about how to fit a snippet into your code.

To do this, I often strip away code that would be good to have, but which might cloud the issue. So I don't guarantee that my examples are good coding practice, but only that they are complete working examples of what I'm talking about. And I warn you in the article when it's not the greatest. Full code can also be downloaded from my Java code repository for this blog (also on the right side of every article here.)

If my articles are of use to you, or you think I can improve things, drop me an email.


*I still do a lot of coding in plain old vi, though I've gotten to like the syntax highlighting in vim as well. If I want an IDE, I usually prefer one of the simpler ones like BlueJ or Greenfoot, though I can bury myself complex ones like Eclipse or NetBeans if I really want to. Occasionally I fire up emacs, though I prefer a stripped version of that, too.


Wednesday, June 27, 2012

Java's Assignment Operators

An assignment operator is a way of putting a new value into a variable.

I covered these briefly in Doing Math in Java, Part 1. Now I'll go into a bit more detail.

The Simple Assignment Operator

The simple assignment operator is =.

It places the value from the expression on its right side into the variable on its left.
This is covered in detail in Left Becomes Right.

Also see the Java Language Specification: The Simple Assignment Operator.

The Compound Assignment Operators

The compound assignment operators are:
+=, "plus-equals",
-=, "minus-equals",
*=, "times-equals" or "star-equals",
/=, "divided by-equals" or "slash-equals",
%=, "remainder-equals" or "percent-equals",
&=, "and-equals",
|=, "or-equals",
^=, "exor-equals" or "caret-equals",
>>=, "signed-shift-right-equals",
<<=, "shift-left-equals",
>>>=, "unsigned-shift-right-equals".

Each of these operators has a variable to assign a value to before it, and an expression that results in a value after it:
variable operator expression

The expression has to result in a value that is compatible with variable's type.

Java will calculate the value of expression,

perform the calculation variable optype expression, where optype is the assignment operator without the equals sign.

Then it will place the result of that calculation into variable.

+=, "Plus-Equals"
Plus-equals adds the value after += to the original value of the variable, then puts the result into the variable.

-=, "Minus-Equals"
This subtracts the value after the operator from the original value in the variable, then stores the result in the variable.

*=, "Times-Equals"
Multiply the variable by the value on the right of the operator, put the result in variable.

/=, "Divided by-Equals"
Same as the above, but for division.

%=, "Remainder-Equals"
This finds the remainder of the variable's initial value divided by the value after the operator. That remainder is then put into the variable.

See Java's Modulo Operator--Wrapping Around for more information on how the remainder (or modulo) operator % works.

&=, "And-Equals"
And-equals does a bit-wise AND of the value after the assignment operator with the original value of the variable, then puts the results in the variable.

|=, "Or-Equals"
Or-equals does a bit-wise OR of the variable and the value after the operator. The result is placed in the variable.

^=, "Exor-Equals"
Exor-equals is short of Exclusive-Or Equals (and it is often written xor-equals). It does a bitwise exclusive-or of the variable and the value after the assignment operator, then puts the result into the variable.

>>=, "Signed-Shift-Right-Equals"
This does a signed right shift of the variable a number of times equal to the expression after the assignment operator. The result is placed in variable.

<<=, "Shift-Left-Equals"
This does the same thing as signed-shift-right-equals, except it does a signed left shift (each bit in the variable gets moved to the left expression times.

>>>=, "Unsigned-Shift-Right-Equals"
This one moves all the bits, unlike the signed shifts which leave the sign bit (highest order bit) alone.

Not Quite the Whole Story
That covers how these operators behave with numerical and other simple values. These operators have other behaviors when used with Strings, Arrays, and other complex value types. That goes beyond the scope of this article, however, more on that can be found at the links given under "Additional Information".

Additional Information
See the Java Language Specification: Compound Assignment Operators, Multiplicative Operators, Additive Operators, Bit-wise and Logical Operators.


Monday, May 14, 2012

Java's Modulo Function--Wrapping Around

I've previously discussed operators in Java, where I gave a brief introduction to the modulo operator, %.

The percent sign is used in many computer languages as a brief, single-character symbol for the remainder of a division, not for a percentage of a number, as you might expect.

What's Left Over

In many calculations in normal day to day life, the remainder of a division is not very important. It's just the odd change left over at the end of doing division. With computer programs, however, modulos can be very useful and powerful.

One of its most important uses is to limit the range of a value. For example, if we're only interested in having a value be a number from 0 to 99, and any value over that is something we don't want, we can use modulo as a way of cutting any number we get down to size. Since the remainder of a division can never be as large or larger than the divisor, we know that any remainder from a division by 100 can never be more than 99 (in integers.) So we can take any number, find the modulo by some number that we want as an unreachable cap on our values, and never get a number that's too big.

limitedNumber = someNumber % 100

limitedNumber will never be higher than 99.

Real World Analogies

A real world version of this is a knob that you can turn around without a stop on it. The knob's setting can vary over a range of values all the way around it. But when you turn it past some point, it goes from its highest setting to its lowest setting.
Radio dial, image by John McComb of Oakland, CA.

For example, a radio dial that goes up in frequency until you hit the top of the radio band, then starts tuning over again from the bottom of the band.

Computer Applications

One of the most common uses of the modulo in computer programs uses that same ability with computer graphics. How many computer games have you seen where an object goes off one side of the computer's screen then reappears on the other side? That's an example of the modulo function. Let's look at an asteroid object that has its horizontal location on screen tracked by the member variable xLoc (short for x location):

Class Asteroid{
    int xLoc, yLoc, xSpeed, ySpeed, size;

We'll assume the class has all the methods it needs to do what Asteroids do. Our instance is:

Asteroid asteroid = new Asteroid();
(If this is unfamiliar to you, you may want to read Creating a Java Variable, Two Steps.)

Now let's say our asteroid is presented on a screen area that is 800 pixels wide and 600 pixels high. That means our xLoc value can vary from 0 (the leftmost location on screen) to 799 (the rightmost location on screen) since we have a screen area 800 pixels wide. Remember, when we start counting at 0 our highest number is one less than the total number of pixels.

We can move our asteroid from left to right as follows:

xLoc = xLoc + xSpeed;

Where xSpeed is how fast we're moving across the screen.

The problem is, what do we do when we hit the right edge of the screen? That is, what do we do when xLoc is higher than 799?

If we want our asteroid to "wrap around" from the right side to the left side of our screen, the modulo operator is just what we want. We can do this to make it wrap around that way:

xLoc = xLoc + xSpeed;
xLoc = xLoc % 800; // Hard-coded screen width, for now.

That will make xLoc always be from 0 (when there is a zero remainder) to 799 (the highest possible remainder when dividing by 800.)

We might have a method in Asteroid like the following:

public int moveHoriz(int howFar){
  // Moves the Asteroid horizontally by howFar pixels on an 800 pixel wide screen.
  // returns the new pixel location.
  return (xLoc + howFar) % 800;

This glosses over a few other problems (like going from the left edge of the screen to the right), but illustrates the use of modulo to bring the object around from right to left again.

An Expanded Example

Here's a more developed example that deals with speeds higher than the screen width, and wraps both ways:

public int moveHoriz(int howFar){
  // Moves the Asteroid horizontally by howFar pixels on a screen.
  // It returns the new horizontal pixel location.

  // We have a screen width available to us in member variable xWidth,
  // and our x location in xLoc.
  // Wraps from right to left, or left to right.

  //Use modulo to trim speed if it's too high.
  if (howFar > xWidth) howFar %= xWidth;

  // Calculate the new x location and return it.
  return (xLoc + howFar + xWidth) % xWidth;

Radio Dial image by John McComb.

Wednesday, March 21, 2012

Java Introspection and Using Collections without Generics

In my prior article on Generics we looked at how to use Generics to associate at type with data stored in a Collection.

You might wonder why would anyone want to store information in a Collection without its type being preserved. Well, it's possible that you'd want to store many Objects of different types in one collection. In that case, the only parent those types might have in common is java.lang.Object. So using a Generic won't do you any good.

But, once you pull that data back out of the Collection, how do you find out what it was?

Fortunately, the object itself has that information stored with it.

There are two easy ways to find out what it is. instanceof can test if it is a specific type of Object:

if (anObject instanceof String) { aString = (String)anObject); }

You can also have an Object tell you its type:

Class myClass = anObject.getClass();


String myClassName = anObject.getClass().getName();

A look at the documentation for Object and Class gives all sorts of useful methods for dealing with classes of data objects in Java.

Here's some sample code:

import java.util.*;

public class NoGenerics2{
// This is an example of using introspection
// to determine types of Objects stored in a
// Collection without a Generic declaration.

public static void main(String[] arg){
ArrayList myList = new ArrayList(); // No Generic declaration.
String myString="Boss Moss";
String yourString="Snorkledorf";

// put the strings into the List

for (Object anObject: myList){
if (anObject instanceof String){
String aString = (String)anObject;
System.out.println("Not a String, Sheriff!");

Wednesday, March 7, 2012

Generics in Java

Generics are an oddly-named thing in Java that associate objects stored in a Collection with a particular type. Let's take a look at a piece of code that uses a Collection to store some Strings. It uses an ArrayList. Here's the code:

import java.util.*;
public class NoGenerics{
// This is an example of what happens
// when you don't declare a class
// for a Collection using Generics.
// It won't compile!

public static void main(String[] arg){
// No Generic declaration.
ArrayList myList = new ArrayList();
String myString="Boss Moss";
String yourString="Snorkledorf";

// put the strings into the ArrayList

for (String aString: myList){
// We can't do String methods on the items from myList.
if (aString.startsWith("Boss")){
System.out.println(aString + ":");
System.out.println("Make sure you spell it right!");
System.out.println(aString + ":");
System.out.println("I am so pretty!");

What happens here to upset javac is that once the String is placed in the ArrayList, its type is lost, and it is known only as an Object. To be treated as a String again, it would have to be cast as a String. If any errors are made in casting the data, the program will fail at runtime, not when it is being compiled--when the programmer has it in their hands to fix it.

Feel free to take the above code and try to compile it to see the error you'll get. It is instructive.

The Fix for Lost Types

In Java version 1.5 "Generics" were added to fix this. Now Collections like the ArrayList can associate a type with the data put in them, and the compiler can do type checking. Here's the above code, with the Generic declaration added:

import java.util.*;

public class Generics{
// This is an example of what happens
// when you declare a data class
// for a Collection using Generics.

public static void main(String[] arg){
// Generic declaration.
ArrayList myList = new ArrayList();
String myString="Boss Moss";
String yourString="Snorkledorf";

// put the strings into the ArrayList

for (String aString: myList){
// Now when we can do String methods on the List items.
if (aString.startsWith("Boss")){
System.out.println(aString + ":");
System.out.println("Make sure you spell it right!");
System.out.println(aString + ":");
System.out.println("I am so pretty!");

Generics = Typed Collections
So if you are going to use a collection on Objects all of a specific type (rather than mixing and matching), put on a Generic declaration.

Monday, January 23, 2012

Java under Mac OS X 10.7 Lion

Lion is the first version of Mac OS X that doesn't come with Java already installed. Earlier versions not only had the Java Virtual Machine or runtime element installed, but they also had the JDK installed, which is the part that lets you write your own Java programs.

Once, Java was an important part of Apple's strategy. They maintained their own version of Java for the Mac and encouraged its use by developers every bit as much as they encouraged the use of Objective-C.

The success of the iPhone and the iPad have changed that, however. Apple decided that Java would not be part of those platforms. The lack of Java is the very reason I've chosen not to get an iPhone. Instead, I get phones with Java so that I can run my own Java applications that I write for my own use.

Now that Lion doesn't have Java pre-installed, what do you do? Fortunately, a deal has been struck where Java is still available for the Mac. It's much the same arrangement as Java for other platforms. In fact, it's easier to install Java on your Mac than any other platform. And you get the JDK along with the runtime (JVM) environment.

Simply use Finder to go to Applications=>Utilities. There, start Terminal. Once Terminal starts, type in the command 'javac'. Your Mac will tell you that Java isn't installed, and let you install it.

I'm pleased that the Mac has not entirely forsaken Java, even if it's not an integral part as it has been. The basic software supplied with the Mac has declined severely over the past few years, but fortunately Java is still available and easy to install when you want it.

Friday, January 6, 2012

Embedded Java

Embedded Java sounds almost like an oxymoron. Taking a high level, large, interpreted language like Java and using it in an application field dominated by assembly and C certainly seems odd. But it's a reality.

For one thing, the microcontrollers of today are not the limited 1K to 2K ROM, 8-bit, 200kHz machine cycle rate CPUs of yesteryear. They're more powerful than the desktop systems of 10-15 years ago in many cases. And we were playing Quake II on those. So maybe Java isn't quite such a stretch, after all.

NanoVM is a small, subscale Java-ish virtual machine that runs on tiny 8-bit microcontrollers like the AVR ATMega8. It's not a full Java, but it covers most of what's interesting to the microcontroller programmer.

The JStamp is a Java development system for the aJile micros. It's also not a full Java SE implementation (what would you do with the extra bits, even if it was?), but it is a verifiable real-time Java system for embedded development.

Also, IS2T has MicroEJ, another embedded Java for a number of processors. Everything from the basics of execution and I/O up to GUIs, SOAs, and safety-critical libraries are available.

I still remember when it was considered laughable to consider a C-language embedded development system. But it has either nudged assembly out of the top spot for embedded development or is close to it, now. Any language that is popular enough can be brought to the task now, and Java is no exception.

It's all just a bunch of ones and zeroes in the end.