Wednesday, December 31, 2008

Learning Swing with the NetBeans IDE

This is where the tutorial begins to get interesting, and for me it was the launch pad to my own first Java applet. I even like the form of the example. It not only contains the essential components of a GUI, but also a tiny bit of mathematics, and it performs a calculation which many of us perform in our head from time to time (if we come from an Anglo-Saxon culture with continental European influences).

The lesson Setting up the Celsius Converter Project is important to read very slowly. Stuff this up and you stuff up your whole project. I think there might be a mistake in it. Certainly I made a mistake on my first run through, and it did stuff me right up.

In Step 1: Create a New Project, the instructions are just fine. Step 2 is fine. Step 3 is also fine in so far as it goes. Obviously if you are using the lesson as a guide for your own custom project you will choose a name which suits you, but that is not the main issue. The main issue here is that nothing is said about packages.

I know I criticised earlier lessons for introducing the package concept too early, but that is because I was using the early lessons to learn Java commands and syntax, and I was not then interested in building a whole application. The situation is now reversed. These lessons are about building an application, albeit a small one, and this when the learner needs to be thinking about placing his or her work in the context of a larger structure.

So I am quite surprised that there is not a reference to packages here, and I am even more surprised that the the create project dialog box does not offer an invitation to assign the project to a package.

Perhaps the answer comes in Steps 4 and 5. Here one is invited to assign the new JFrame to a package. The instruction is in very small print and would be easy to miss or gloss over. There is no mention of the significance of packages or the implications of assigning a class to the wrong package.

In VB, the project or project location is all important. What Java calls a JFrame, VB calls a form, and the file defining the form sits in the project folder, and can be used or dropped by the project, or indeed used by future projects, located in the same folder. So in VB, if you stuff up a project and need to start a new one, you can still use all the graphics created in the first incarnation of the project, without having to think too hard. Obviously you can reuse code in Java (that's what packages and classes are all about), but if you don't assign a class to a package correctly in the first place, using it all may be difficult, and using it in future projects may be nearly impossible.

Tuesday, December 30, 2008

Getting Started with Swing

Getting Started with Swing is the first lesson in the so-called Swing Tutorial. The lesson has two parts: About the JFC and Swing and Compiling and Running Swing Programs.

The first is as dull as it sounds, albeit of theoretical importance. It is essentially a reminder of the transparency of Java - a reminder that the power of Java lies in the huge collection of classes, already written by someone else, but made available for everyone. So while you can use a development environment like NetBeans, you can also access the functionality of the classes with hand written code.

This is important. If you want to program in VB (to create a Windows app) but you don't like the development environment, you are pretty well buggered. But if you want to create a GUI with Java, and you don't like NetBeans, you can either use another development environment, or you can do the whole thing with a text editor, provided you follow the rules very carefully.

The second part of the lesson is also very dull (another sodding "Hello World" variant), but it includes a moderately interesting link in small print. This is Running Tutorial Examples in NetBeans IDE. A link is provided to download NetBeans (for anyone who missed the riveting "Hello World!" for the NetBeans IDE). After installing NetBeans, you can download one or more example projects. Instructions are then provided on how to load a project into NetBeans, and from there compile it and run it.

Monday, December 15, 2008

Swing

Since my last post I have been musing on the question of where to go next. Should I plough through more turgid lessons on the language or should I have some fun with the Swing thread. After some deliberation I have decided to go with A Brief Introduction to Swing.

The first branch of this trail is a philosophical piece entitled What is Swing? It is best to ignore this as the tutorial tends to get muddled when it tries to be philosophical. The second branch, A Swing Demo, is much more fun. It talks you through a real applet, and it inspires enthusiasm because it is so neat, and it works so well.

The Swing Features trail is pretty much a reference document with illustrations of what VB would call GUI objects, but which here are called Swing components. There is in my opinion rather too much space devotes to the so called "Look and Feel", and then there are the usual sections on internationalisation and accessibility, which in a politically correct world they have to put in, but which I'm afraid I find rather dull, and skip over.

The post interesting link in the Swing thread is given in very small print. The same link also appears on the Tutorial home page, also in small print, under the heading Creating Graphical User Interfaces. It is the trail: Creating a GUI with JFC/Swing. This is where you should go to learn about Swing, by doing rather than just reading. And this is where I shall begin in my next blog entry.

Saturday, November 8, 2008

Setting Path as an Environment Variable

Since 1995, when Microsoft replaced the old 16 bit Win3x with it's 32 bit operating systems, WinNT and Win9x onwards, Windows users have not really had to think about defining paths as environment variables, unless they have had the misfortune still to be running a 16 bit application from the command prompt. So when lessons in the Java Tutorial make references to setting path variables, I feel as if I have been time warped back 15 years.

The subject of my last blog talks about setting the class path, and the "Hello World" for Windows lesson in the very first trail obliquely embeds instructions about path settings. And when I say oblique, I mean very oblique. First they set you up to hit an error. Then they provide a link to a troubleshooting page. And from there there is another link to instructions on writing a path to javac in the user environment settings. Considering the level of detail given on simpleton tasks, like saving a text file, or basic navigation at the command prompt, and considering that this is supposed to be a really easy lesson, intended to make people like Java, not hate it already, the instructions on the javac path are very badly written.

And it's not just me. I keep a vague eye on the Java Tutorial Discussion Group. Here is an example of someone else who had trouble with the path settings. The only third party response in this thread was singularly unhelpful, so before proceeding my journey through the Java tutorial I shall revisit the early instructions on path settings.

The "Hello World" for Windows lesson is both irritatingly simplistic and condescending in some ways, and incomplete in others. For example in the section on creating a source file it gives the option of downloading the source file or typing the code in longhand. Why doesn't it mention the option of copying and pasting? In the instruction on saving the source file it addresses users as they have never saved a file from a Windows App, but it gives no guidance on the file location strategy. It assumes the user has already created a folder for their source files, and it breaks with Microsoft advice not to put user/application stuff in the root directory of the system drive. And to compound the confusion, having suggested putting source files into C:\Java, a couple of paragraphs later the user is taken to D:\Java.

And then without a whisper about path settings the lesson says (quote):

Now you are ready to compile. At the prompt, type the following command and press Enter.

javac HelloWorldApp.java

The compiler has generated a bytecode file, HelloWorldApp.class. (unquote)

All of which is regrettably not true. The system has in fact generated an error message:

'javac' is not recognized as an internal or external command, operable program or batch file

The pitiful excuse for omitting to say anything about path settings in the lesson might be that the release notes include an optional instruction to update the path variable after installing the JDK. So on the one hand the user is assumed to such an idiot that they need screen shots to help them save a text file or run the dir command, while on the other they are assumed to be sufficiently expert to read the release note in intimate detail and to complete even the optional instruction in advance.

I have mentioned before that I am working on an old and slightly cranky computer, so that setting the path as an environment variable didn't work for me doesn't necessarily mean the instructions are wrong. But it does indicate that doing so is not 100% reliable. So to assume in the lesson that the variable has been set, and that it will work is a bad writing strategy.

In my early blog, I suggested that a possible cheat would be to copy the source file into the jdk6\bin\ folder and run javac from there. But after filling what is supposed to be a system folder with my own rubbish, I accept that this is perhaps not the neatest strategy. Instead I recommend putting a short batch file in the Windows home directory. You can use this both to navigate to wherever you keep you keep your java working files and to set a temporary path to the jdk6\bin\ folder. This path will stay current as long as the command window remains open.

My batch file is called cd1.bat and it contains just 2 lines:

cd My Documents\Current\Java
set path=C:\Program Files\Java\jdk1.6.0_03\bin

So now I can keep all my java working and experimental files in a logical place and compile source code without hassle. To get there I just enter cd1 at the opening command prompt.

And I contend that instructions along these lines would improve the "Hello World" for Windows lesson.

Sunday, October 19, 2008

Managing Source and Class Files

This lesson obliquely answers a question not answered in the earlier lesson on creating packages. Quoting from the lesson: "Many implementations of the Java platform rely on hierarchical file systems to manage source and class files, although The Java Language Specification does not require this".

So in theory, it seems, you can put package members anywhere you like, but in practice it seems advisable to file them in an orderly way. If you use NetBeans, it will do the filing for you, with each project in a directory or folder and class files and source files in subdirectories or subfolders.

If you program by hand, this lesson recommends that you put package members in a folder which corresponds to the package name. It also suggests that (like NetBeans) you put your source files and compiled files into separate subfolders. This all seems very reasonable and sensible, but I still can't fathom why the information was not put up front in the lesson on creating packages.

And that concludes the Learning the Java Language trail.

But the lesson ends with a paragraph about setting the class path. And as my first Java Blog included a beef about the path instructions, before I start another trail, I shall revisit the path issue.

Friday, October 10, 2008

Using Package Members

This is an important lesson. Notwithstanding my comments on the linguistic style of the previous few lessons, java packages are central to the java model for sharing code.

Microsoft uses what they call dynamic link libraries (dll's) to store code shared by many applications. When you, the ordinary programmer, create an application which uses an object defined in a dll, VB, or whatever other programming application is being used, makes a note of it, and when you distribute the application, that, and any other dll you have used, gets included in the cab files. In contrast with the Java model, your own code is stored (after compiling) in an executable, and is not readily usable by other programmers or applications.

In the java model, it seems that even the most humble programmer, has the option of making the classes, which they create, usable by others. And because they have the option of doing so, they are encouraged to organise their work in the same manner which is required of paid programmers working in large organizations. Indeed they are more than encouraged. If they don't follow the rules, even for a very simple application, they are likely to come unstuck, as I discovered to my cost.

In a later blog, I shall describe in detail the fun I had with NetBeans, but for now all I need to say is that to make my code work, I had to create a custom class, and because I did not read this lesson properly, I attached my class to the wrong package, failed to import it properly, and nothing did work.

So the first rule of thumb is that if you are writing an application comprising objects from more than one class, attach all the class files to the same package. Now obviously if you want a graphic interface, you will apply code written by others, and which will belong to other packages. But if you are using a tool like NetBeans, a lot of the thinking on that side of it will be done for you. Where you have to be careful, is when you start creating custom objects from custom classes, because you have to assign everything you create to a package, and it pays to have done some thinking in advance as to how you are going to do this.

The "Hello World!" application sidesteps all these issues, because it doesn't call on any external code. It is entirely self contained. So it doesn't need to be assigned to a package. It therefore represents a very bad template from which to learn Java.

The BicycleDemo is more misleading still, because it does create objects from a class, and neither it nor the class from which the objects are created appear to have been assigned to a package.

In practice, it seems, you need to use packages, and if you create an object from a class, if the class does not reside in the package in which you are writing, you need to refer to the class by its qualified name (as defined in the lesson), or you need to import either the class or the whole package (again as described in the lesson).

Monday, October 6, 2008

How to Make a Java Package

After a singularly unconvincing lesson on the theory behind packages, there follows one on how to make them. And the opening is not auspicious: "To create a package, you choose a name for the package ... ". Gosh I'd never have guessed that. Never having created a file before, or a folder, or zip file, I'd never have guessed that you have to "choose a name" for java packages.

The level of these tutorials is not consistent. One minute they use undefined terms, and just assume you can work out what they mean. And the next go down to a level which can only be described as inane.

Is it Sun, is it Java, or is it Americans who just can't express themselves in writing. It can't be Americans. I had my doctoral thesis proof read by an American whose English was impeccable. It must be mainstream programmers, who just aren't used to writing in English. The bottom line is that it makes the learning process long, slow and hard.

After reading the opening paragraph fifteen times, the message seems to be that creating a java package involves not so much grouping a bunch of source files into a folder or zipping them into an archive, but rather a "belongs to" statement has to be included in each file. That's OK. It's not something I've had to do manually before, but now I've been told, I'll try to remember it. But why can't it be explained simply, and explicitly?

The second paragraph in the lesson is shorter, clearer, but still amazingly trivial. The "belongs to" statement must be in the first line of the source file, and check this out, each source file can only belong to one package - as if one is used to files having membership of multiple folders or archives!

There follows an insert containing more tangential gibberish, and then we see excerpts from six source files, each with an identical "belongs to" statement in the first line. Two contradictory thoughts arise from this. First do we really need six illustrations of such a simple construct? Second, is that it? Is that all you do to create a package? The location of the files in the local file system is apparently irrelevant? There is no compression or archiving of the source files into a single (dare I say) package? Apparently not. A java package is apparently just a collection of files which share a common opening statement.

Sunday, October 5, 2008

Package Theory

Here is a trail which should apply to everyone. Let us hope it is useful and easy to understand. Let us hope it is written in English.

Let us hope in vain.

Even the opening sentence of the opening lesson includes an undefined term. "To make types easier to find and use ... programmers bundle groups of related types into packages." From all the preceding lessons I hardly recollect the term type being used, let alone defined. A quick search through the lessons revealed one the more esoteric lessons: "Enum Types", using the term in the same context, but again with no definition. It is just assumed that you can read the authors mind, or can work it out for yourself. This is a bad assumption in a tutorial.

But then, as if as an afterthought, there has been inserted into the text a definition. Is it a definition of "type"? No; it is a definition of package, which is fair enough since that is the title of the thread. But the "type" is central to the definition of package: "A package is a grouping of related types ... ". And as an afterthought to the afterthought, a sort of apology for a definition is appended: "Note that types refers to classes, interfaces, enumerations, and annotation types." It's a pity the author doesn't know how to conjugate verbs, and its odd that the definition seems to be recursive, but it's better than nothing, and the author could, with grace, have stopped there. But perhaps a sixth sense told him (or her) that what had been written so far was grammatical and logical gibberish, so he (or she) fumbled on, still in the insert intended for a short crunchy definition, but now on the tangential path of a long and rambling essay: "Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces".

Why not say that in the first place? Why not open the lesson with a simple definition, such as: a package is a group of related classes and interfaces? That would be too simple I suppose; not highfalutin enough.

The gibberish continues: "The types that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on. You can put your types in packages too." Well thank you very much. But besides making our code files look pretty, why should we want to?

The text continues with the silliest example imaginable. The world is awash with graphics software, and has been for twenty years or more. This may be new and exciting for the boffins at Sun, who never properly weaned themselves from the command line, but why would anyone in the real world want to write code for creating plane geometrical graphics. And none of the reasons for bundling these files into a package struck me as particularly compelling.

Wednesday, October 1, 2008

Generics

When I read the trail on Generics the first time I fogged out. And when I read it a second time I fogged out again.

For me, key phrases include:

        // Imagine this is one part of a large application
// modified by one programmer.
        // ... and this is another, perhaps written
// by a different programmer

These phrases are a let out for me because I am a sole programmer working from home on a non-collaborative project. So the situation described with not apply.

Another key phrase is: "In any nontrivial software project, bugs are simply a fact of life". This tells me the trail has something to do with error trapping. This in turn raises two questions in my mind.

First, why is there nothing about error trapping or bug avoidance in the trail heading? Second, why is the first lesson which even mentions errors and bugs so incredibly esoteric? Why not have a basic lesson on bugs first, and then put the weird one in an appendix somewhere.

All in all I rank this trail below reference. For beginners I'd rate this a skip altogether trail.

Tuesday, September 30, 2008

Numbers and Strings

The Numbers and Strings trail is also pretty much a reference trail, but there is a catch, to catch out the unwary beginner. Some of the lessons need to be read very carefully, before you begin programming.

In the languages I've used previously, a number is a number and a string is a string, and that's all you really need to know, besides how to convert one to the other. Not so in Java. Java is the language where all objects have to belong to classes, classes belong to superclasses, and superclasses belong to an object. So to expect a number simply to be a number and a string simply to be a string in Java would be naive.

No, in Java, numbers belong to a number class (with subclasses for the number types), strings belong to a string class, and even formatting belongs to a formatting class.

The implications for programming with numbers don't seem to be too great because "most of the time" you are allowed to use the "primitive types". So when you declare number variables, the following code (quoted from the number class page) is acceptable:

int i = 500;
float gpa = 3.65f;
byte mask = 0xff;

But for some reason, best known to the language designers, you can't do this for strings. They allow it for single characters (quoted from the character page):

char ch = 'a';
char uniChar = '\u039A'; // Unicode for uppercase Greek omega character
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
// an array of chars

As if anyone would ever code with singles characters!

But for strings you have to create an object from the string class. Here is the code (quoted from the strings page), which they use to introduce the idea:


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println(helloString);

I thought this was so silly, the first time I read it, I completely ignored it, to my cost when I started coding. I think I was put off by the unlikely (to the point of absurdity) construct of building a string from an array. But the fact is you can't declare a string as a primitive type, like you do in VB and other languages. You have to create an object:

String myString = new String("put anything here");

Having done this you can treat it more or less as you you treat the primitive string type in other languages.

The other crucial lesson in this trail is "Converting Between Numbers and Strings".

Converting from numbers to strings is fairly straightforward. It seems you can force it simply by concatenating a number with a string or plonking it into a container intended for strings. I'll illustrate with my own code:

int num1 = 2;
int num2 = 2;
MathItemlabel.setText(num1 + " + "
+ num2 + " = " );

Here I have declared two primitive integers, num1 and num2, and converted them to text by concatenation with strings, so that they can be placed in a test field. That was pretty easy.

Converting from strings to numbers is a bit harder. First of all it seems that you have to convert to a float. Then if you want say an integer, you convert the float to an integer. Again, I'll use my own code:


String answerString = new String(Anstextfld.getText());
float ansf = 0;
int ansi = 0;
ansf = (Float.valueOf(answerString) ).floatValue();
ansi = (int)(ansf);

First I created a string object and filled it with text from a field. Then I declared primitive float and integer variables. Then I converted the string to a float and the float to an integer. Then I could do what I wanted with the integer.

Monday, September 29, 2008

Interfaces and Inheritance

The next trail is headed "Interfaces and Inheritance". I have already suggested that real beginners can manage without this stuff, and I think they could safely skip this trail.

I shall plough on, because my last project used a lot of code, and if I am starting again in a new language, I might as well familiarise myself with any techniques which might make my coding more efficient.

Reading the blurb on Interfaces it seems these might be used in large collaborative projects, where different, possible competing entities write code, but they agree to operate within a common structure; and that's where the interface comes in. The vendors of programming software might also use them.

Inheritance has already been explained quite well with the bicycle analogy, and these lessons just seem to flesh that out a bit further. Placing an object at the top of the superclass hierarchy seems typically contrary, but at the end of the day, if it works, who gives a shit.

In summary, this trail is a reference trail. If anyone ever needed to use these constructs they'd refer to it.

Sunday, September 28, 2008

Nested Classes

The lesson on Nested Classes is another which could be skipped in its entirety by the beginner, without loss of continuity. And while the tutorial argues enthusiastically that: "There are several compelling reasons for using nested classes", I can't see myself using them for some time, if ever.

I read the sample page with an open mind, prepared to be persuaded otherwise, but the example was so trivial, it did the opposite. I remain convinced that the home programmer can live without nested classes. And the Summary page wasn't really a summary, and could have been appended to the opening page, thereby reducing bloat in the table of contents.

And if you ignore the questions and exercises, this concludes the trail on classes and objects.

Saturday, September 27, 2008

More than a beginner might need on classes

In an earlier blog I suggested that this tutorial might sometimes offer forks, with career programmers following one path and real beginners following another. And the More on Classes lesson perhaps represents the point on the current trail when the two paths might part. With what we've been told already, an enthusiastic beginner could create classes and objects and write some useful code.

For the sake of completeness, I'll continue on the trail, and perhaps make the occasional snide remark on the way.

Lets begin with Returning a Value from a Method. If I entitled a lesson thus, I'd open it with a statement about returning values from methods.

And if I wanted to open a lesson with the sentence: "A method returns to the code that invoked it when ... ", then I'd entitle the lesson something like "Code Execution Paths". Heading a lesson "Returning a Value" and then talking about paths through code is at best confusing.

Methods returning values are like functions in VB. To be honest I never used them, or at least, not home made ones. But I am sure there are others who did, and they might enjoy this page more than I did.

The next lesson on the "this" keyword was straightforward enough. There's something similar in VB; I've forgotten what it is now.

The lesson on controlling access is probably interesting to programmers working for large corporations, but it was deadly boring to me.

The lesson on class variables gives an interesting illustration of how to use a class/static variable in conjunction with the constructor to record the number of objects created from a class. It goes on to show how to use a class/static method to access the variable without creating another instance of the class. I'm not sure when I'd ever use this, but it was interesting, and quite clever.

The lesson on initialising fields gives an interesting insight as to when constructors work better than initialisation on declaration. This little titbit could have been put in the lesson which introduced the constructor, and the next one on the topic, and it would have made a lot more sense of those lessons.

The summary lesson is fine, but again, I was always taught the summary and introduction should contain similar components. If I were writing these tutorials, I'd include all the essential components of this summary in the very first lesson on classes, albeit perhaps with different colours for compulsory items (instance variables, methods), and optional items like constructors and static variables and methods, at at least a basic explanation of when and how to use them.

Friday, September 26, 2008

Classes and Objects

There follow two lessons, which are straightforward and easy to follow, so there is no need to say much about them. The Passing Information lesson gives a nice illustration with code to compute monthly payments on a home loan. The rest of the lesson is fine, except that a paragraph on circles refers to another lesson without giving a hyper-link. It's not the end of the world, but it is annoying. I'll provide one.

And the top page of the Objects group is nicely explained, with links to the code for the classes behind the objects it uses. This is thoughtful, and certainly aids understanding.

Then it all falls apart with the lesson on Creating Objects. I'm not quite sure why we need this page. We've already seen objects created in the first lesson on classes, and we've seen them created in a different way in the second lesson on classes (with constructors). When I first read this lesson I wondered whether it was written deliberately to confuse, rather than to encourage new Java users, to put off the unworthy.

The term Instantiating in my opinion introduces unnecessary confusion for migrants from Visual Basic because it is used there in a slightly different context. VB doesn't use classes (or didn't the last time I looked), but if you write code for an object you can instantiate that object as often as you like. The effect is almost exactly the same, except that you don't have to call the first object a class; you just call it an object.

If I were writing the paragraph headed "Instantiating a Class" I'd call it "Creating an Object from a Class". It has the same meaning, but it just seems to me more consistent with the Java model and less VB-like.

And the paragraph "Initializing an Object" I'd call "Initializing a Reference Variable", and I'd put it right after the paragraph headed "Declaring a Variable to Refer to an Object" so that it flows and makes sense.

After the confusion of that lesson, the lesson entitled "Using Objects" is nicely laid out and explained.

Thursday, September 25, 2008

Constructors revisited

"A class contains constructors that are invoked to create objects from the class blueprint.", says the lesson entitled Providing Constructors.

So where is the constructor in Hello World? Where is the constructor in the first bicycle?

For clarity, let's set out the code for the first bicycle (Version 1):

class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:"+cadence+
" speed:"+speed+" gear:"+gear);

}
}

and lets compare this with the bicycle with constructor (Version 2):

public class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startCadence,
int startSpeed,
int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}

To my (Java-virgin) eyes, the essential difference between the two is that in Version 1, the fields cadence, speed, and gear are initialised upon declaration, but in Version 2 they are not. Instead you have this thing called a constructor which essentially does exactly that.

I concede that creating a bicycle with particular parameter values is quite neat from Version 2

Bicycle myBike = new Bicycle(30, 0, 8);

whereas to do the same from Version 1 is a bit more clumsy:

Bicycle bike1 = new Bicycle();
bike1.cadence = 30
bike1.speed = 0
bike1.gear = 8

Unless of course you have a class of objects which always (or nearly always) opens with the same values, in which case you simply plonk those values into the field declarations of Version 1 of the class. This is not an unreasonable assumption even in the case of a bicycle. Why should a bicycle not start with a zero cadence, zero speed, and in gear 1?

But this is all beside the point really. My criticism of the Java Tutorial in this lesson is not whether or not you can write neater code with or without a constructor. It is that the idea is badly introduced and poorly explained.

The opening sentence: "A class contains constructors that are invoked to create objects from the class blueprint" is confusing for many reasons, not least because we have seen classes without constructors and objects created without reference to them.

The fudge provided by the lesson to excuse this is: "Although Bicycle only has one constructor, it could have others, including a no-argument constructor". This is like saying a man with no legs has two no-leg legs. It's ugly and silly.

I don't have time or the inclination to rewrite the entire tutorial. I am still learning myself. But I can think of at least two ways to introduce the idea of a constructor more coherently, so the lessons flow better.

First in the What is a Class lesson, when Bicycle is invoked:

          // Create two different Bicycle objects           Bicycle bike1 = new Bicycle();           Bicycle bike2 = new Bicycle();

There could be an explicit reference to the brackets, and explanation as to how they can be used and why they are empty. And if it is poor coding practice not use constructors, then this should be explained sooner rather than later.

Second in Constructor lesson, don't open with a sentence which implies that this is the only way of doing things (which it patently isn't), but make an explicit reference Version 1 of the bicycle, and explain how adding a constructor to the class might in some circumstances make the code to create objects from the class neater.

And again, if there are other reasons for using constructors, such as that the compiler looks for them, then this should have been explained earlier, and it should be explained better and more fully, with examples of good code, and examples of code which will not compile.

Wednesday, September 24, 2008

Declaring Classes and Defining Methods

The Declaring Classes page obliquely refers to Inheritance and Interfaces, but just as the previous page on this topic said very little on why you would use an Interface, and when you would use one instead of or as well as a superclass, this page also assumes you would know when and why you would use either or both constructs.

To be fair there is a promise to talk about them later: "The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords", but there are two things wrong with the promise. First there is no hyperlink, so the reader is left to scurry around looking for lessons "on interfaces and inheritance". Second, we have already lessons on interfaces and inheritance, which say very little about how and why when you would use one rather than the other.

My general observation of these tutorials is that the language mechanics are better described than the more abstract ideas. This applies to the Defining Methods page, which sets out the rules quite clearly.

Tuesday, September 23, 2008

The Constructor

This takes us to the third lesson in the language trail, Classes and Objects, and the first lesson is a closer look at classes.

The lesson subtly introduces a new concept: That of a "constructor". This term appears neither in the closer look at hello world, nor in the first lesson on classes. But it is not formerly introduced, nor is it explained. We are just told that there is one of them in the bicycle class. Which fact is interesting in itself, because if there is one in the bicycle class, why wasn't it mentioned the last time the bicycle class was set out before us.

It wasn't mentioned because it wasn't there. It wasn't there on the page, and nor was it in the sample class available on a hyperlink. Now I know these are all just illustrative examples, but I really think the learning process for the beginner would be made easier if the sample code for examples given a name, like bicycle, were kept consistent.

As to what the constructor does. Well it seems to assign values to variables/fields. Not quite sure why that can't be done when the variables are declared, but perhaps it will be explained later.

Monday, September 22, 2008

Java Language Basics

I was a bit down on the Concepts trail. Not so language basics. This one read just fine. I guess the nuts and bolts of all programming languages have to have aspects in common, because at the end of the day they all have to perform similar tasks.

If I have a criticism it is not of what is there so much as what I feel is missing from the page on variables.

When learning VB there are whole chapters on the life of variables, but these Java tutorials don't seem to mention the concept explicitly. I posted a question on the subject in the tutorial discussion forum, but I was not really happy with the replies.

I'll set out the problem again here. Essentially I had used NetBeans to create what in VB is called a form but here seems to be called a JFrame. The Jframe had a button a text field and labels. I coded the button to put a string in one of the labels. So far so good. But I wanted the button to remember what it had done after the event code had finished executing. I wanted the button to store information in a variable (or field) defined by me.

According to my understanding of the theory set out in the Java tutorial, the button is an object belonging to a class, and it has a number of fields, defined by the class. And in the NetBeans IDE I could see these fields listed in the properties window. But what scope do I the user have to add fields to this list, and how do I do it?

In VB a form has code associated with it, the user can declare variables in that code, and any object on the form can use those variables, and the variables stay alive for as long as the form. This is very handy. And since VB is a widely used language, I think the Java tutorials might make explicit reference to this, and then compare and contrast the rules in the two language.

I tinkered around for hours but I could not apply this VB style variable declaration in a JFrame.

In the end I created and compiled my own class with all the "fields" I needed, and then put an object from that class on my JFrame. Actually getting that to work was also something of a nightmare, but I shall describe that in a later blog, which focuses on the Swing tutorial.

Sunday, September 21, 2008

Inheritance, Interfaces and Packages

As I ploughed on through the trail, I began to feel there might be merit in a Java Tutorial for ninnies, such as myself. Such a tutorial would include the sections Objects and Classes, and then it would stop for a breather, and perhaps provide simple (but not too simple) practical examples on how it all works. Perhaps later in this blog I might record how I applied the previous two lessons, but for now I'll plough on, because that's what I did when I first followed the trail.

I thought the bicycle analogy worked really well to explain the concept of inheritance, but I couldn't help racking my brains and wondering when I would ever apply the knowledge myself.

And after struggling to absorb the rulLinkes on Objects and Classes, when I read the page on interfaces, I asked the questions: Why? What is this for? How does this help me to write good code? When would I or when should I use an interface?

I'd wager that 90% of grass roots programmers, by which I people working for themselves as opposed to software giants, would use an object once and only once, in which case the class is already a redundant layer of classification. Under such circumstances, adding an interface would just add another redundant layer.

So I reached the page on packages after struggling with two pages which didn't really apply to me, and I was tired, and didn't properly absorb it. Now I know it is in the essence of hypertext that the reader can jump from one page to another. But it is also human nature, when one is following a trail, to follow the trail. I perhaps another way of improving these tutorials for real beginners would be to offer forks in the trail, with one path for professionals or career students, and a shorter path for real beginners or amateur and part time programmers.

And even when I read the page again, I am not sure how it helps me to produce and distribute my own Java application. I guess it is nice to know that people have written hundreds of classes and interfaces, and nicer still to know that they have organised them neatly into packages and libraries. But how does that help me, the Java learner, to write my application?

For example, if my application uses a class written by someone else, when I distribute my application, do I need to distribute the whole package, or the whole library? Do I even need to distribute the class file? Or do I assume the whole package/library structure remains stable over time and will already reside on any computer with the current JRE installed. The answers to these questions may be obvious to the experts, but they are not obvious to me, and I'd wager they are not obvious to many aspiring java programmers using the Java Tutorial.

Saturday, September 20, 2008

Object-Oriented Programming Concepts

After the irritation of "Hello World!" is was a pleasure to start a thread with some substance.

I liked the description of objects, and analogy between the state and behaviour of real world objects and the fields and methods of software objects. The diagram was a bit weird. At first I thought there were 3 methods and 3 fields with methods on the left and objects on the right. But I guess displaying an abstract idea with a diagram is always tricky, and if you asked a hundred illustrators to do this they'd come up with a hundred ideas. I might have drawn it differently, but it focussed my thoughts and was still an asset to the thread.

I liked the bicycle analogy, especially when it was extended to the description of classes. But when the idea was converted to code, I found the methods disappointing. I guess because I like physics, in the apply brakes method, I was looking for something about forces, masses and coefficients of friction. I know it has to be kept simple, but these methods were too simple, to the point of being confusing.

If you think of a method as being like a mathematical function, in the function f(x) something always happens to x. For example:

f(x) = 2x
f(x) = x + 2
f(x) = x - 2

But in the tutorial, the change cadence method is more like:

f(x) = a

You don't need a function for this, and you don't need cadence method in the tutorial. Having it there doesn't add to the learners understanding of what a method is and does; it detracts from it. If all you are doing is assigning a value to a variable you can just assign it. To clarify what I mean, if one has previously created an object mybicycle from the bicycle class:

 cadence    =   myBicycle.changeCadence(newValue)

is tautologous gibberish, when you can do just as well with:

 cadence    =    newValue

Besides, I bet there are many people out there in the tutorial readership who don't know what a cadence is, especially those for whom English is not their first language. If anyone from Sun ever reads this, my advice would be to drop the changeCadence method, and either drop the changeGear method, or rewrite it as:

       void changeGear(int deltagear) {
gear = gear + deltagear;
}

where deltagear can be positive or negative. It's still boring, but it's not completely redundant.

Friday, September 19, 2008

Hello World

The next lesson is entitled "A Closer Look at the "Hello World!" Application", and it opens with the phrase "Here again is its code".

If I opened a lesson thus, I think I would quote the entire content of the source file. It is after all only 8 lines. But in the actual lesson, the non-comment section of the code is quoted, and guess what the lesson talks about first: comments. Perhaps it is a trivial point. Perhaps no one else has noticed. But for me, the non-java programmer, it caused me to stop, to read it twice, to work harder to understand what it all meant and where it all fitted in.

I guess the rest of the lesson flows OK, but if I were feeling picky, and I am, I'd make two comments.

The first is the Hello World is a really feeble tool to illustrate programming concepts. I grant that some of the important components are in there, but it's so dull, and it is not thorough.. A practical programmer want a method to do a little more than simply display an inane message. There is no explicitly declared object (to the non-java programmer this whole class thing is gibberish, until it is properly explained), and there are no defined variables or fields.

The second is that a practical illustration (like this, with the main components of code highlighted) might perhaps be better placed after or at the end of the theory trails.

Thursday, September 18, 2008

Where to start?

Editorial Note:

This blog was written three years ago, since when Sun has been acquired by Oracle. Pretty much all of the links to the Java tutorial have therefore become wrong. I shall attempt to correct as many as possible, but if I miss any, please use the link given below to get to the main page, and navigate manually from there.


The documentation that came with JDK6 led me to “The Java Tutorials” at:


http://download.oracle.com/javase/tutorial/index.html


Full of optimism I hit the link to the “Getting Started” trail.


The first link in this trail is entitled “The Java Technology Phenomenon”, and without any hard feelings intended, I have to describe it as pretty boring. If I might generalise from a very small sample, I think a possible criticism of the whole tutorial is that it is written by some of the leading experts in the field – people who have been working for so long with this stuff that they have spinal reflexes for many tasks, which the new user might find quite daunting. They are also ideological purists. They really are interested in the whole theory of the thing.


To an academic, or even a student who wants to make a lifelong career of programming, this stuff might indeed be interesting. But to an old dog like me, who just want to write a few lines of code, it’s information I’d rather see in an appendix at the back of the book, rather than in my face in Chapter One.


The second link in the thread, Hello World, is more practical, if a little tired, and irritatingly trivial.


It is in my nature to be methodical, so I followed the trail in sequence, beginning with “"Hello World!" for the NetBeans IDE”. Dutifully, I downloaded NetBeans and installed it. I should perhaps add at this stage that I am doing all this on a rather old laptop. It is a PIII with 500 MBRAM. It is obviously not a tool for programming in a sophisticated IDE. For me it is more a diary and travelling companion. So it is not in the nature of a complaint when I observe that NetBeans is quite a resource hungry application. It took almost two minutes to load on my old box, and took system memory utilisation over 80%. So for anyone out there with less than a brand new machine, NetBeans is not a light app. Using it to draft “Hello World!” is a classic sledge hammer to crack a nut!


When I moved on to the page headed “"Hello World!" for Microsoft Windows” I thought my trusty old PIII box would perform the task swimmingly. Apart from the JRE, which was already installed, all I needed was a text editor.


But it was not to be the case. I got the message “'javac' is not recognized as an internal or external command, operable program or batch file”. And when I went to the troubleshooting page and followed the instructions, it still didn’t work. I know older machines exhibit idiosyncratic problems, and I appreciate that all this stuff is free, but it was still infuriating.


The only way I could get the LinkHello World! source code to compile was to copy the source file into the jdk6\bin\ folder on my computer and run javac from there. I used this cheat for the remainder of the tutorials.