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.