Tag Archives: java

Is Java pass-by-value or pass-by-reference?

The question if Java passes parameters by value or by reference seems to be one of the things newcomers to the Java language stumble upon quite often.

In general the answer is simple: Java is always pass-by-value.

What does this mean?

Pass-by-value means that you get a copy of the passed in object to work with, as opposed to a reference to it.

Let’s exemplify.  Assume we have a method that manipulates a List object:

public void updateList(List list) {
    ..;
}

Now, assume we’d like to replace the passed-in list with another list we’ve created inside the method.  We might like to do something like:

public void updateList(List list) {
    List myList = new ArrayList();
    // add objects to myList
    list = myList; // replace list with my new list? *WRONG*
}

However, if we test this new method we’ll find list has not changed at all.

This is because list is a copy of the object we passed-in to the method, and not the passed-in object itself.  list has been passed-by-value!

So, are we unable to change variables that are passed-in to a method in Java?  Can we only change them by returning a new object?

No.

And this is where the confusion sets in, because while we’re unable to replace the passed-in object list with another object, we’re perfectly allowed to manipulate it’s member objects.

Basically this means if we want to replace a passed-in list with our own list we must do:

public void updateList(List list) {
    List myList = new ArrayList();
    // add objects to myList
    list.clear(); // empty passed-in list
    list.addAll(myList); // replace passed-in list with my new list!
}

Since we never try to replace list itself, the whole method works just fine and does what we expect.

CHARVA: A Java Windowing Toolkit for Text Terminals

Looking around for an easy way to create applications with text GUIs for running over SSH terminals I came across CHARVA. CHARVA’s API copies Swings, it unfortunately is not built on top of Swing but is a copy of Swing. This forces implementers to import classes in the charva.awt and charvax.swing packages instead of traditional awt and swing classes. However, the result is rather nice, at least if you’re looking to run applications off a server on a simple Point-of-Sale or Point-of-Service (POS) terminal that may not even support graphics.

In my case I’m looking into making a simple app that I can use to keep track of passwords, both when I’m at home (regular swing) and when I’m away (at work or similar) and only able to access the application via SSH (CHARVA).

For more info, check out CHARVA here: http://www.pitman.co.za/projects/charva/index.html

Compiling to different versions of Java in Eclipse

I’ve just had the rather unsettling experience of trying to deploy a new jar file (one I recompiled after some changes). This file were to be deployed on a rather old set up of Java 1.4.2. On first try everything broke with the classic “Unsupported major.minor version 50.0”.

So I went back to the drawing board. I installed java 1.4, and made sure my development Tomcat was running it. Then I did some research and found out how to make Eclipse compile 1.4 compliant code. I started and I got the same error still.

Once I figured out what was wrong I realized I was an idiot (Doh!). The error I’ve gotten wasn’t for any file part of the jar I was trying to deploy but for “index_jsp”. The thing is my Tomcat compiled my JSP:s into class files and never looked at them again until they were changed. I am sure there’s several ways to solve the problem, I just went and deleted the files in the “work”-directory (those pertaining to my Context).

The preferences window for setting source and target versions for java compilation
The preferences window for setting source and target versions for Java compilation

Now over to how to make Eclipse code projects to a certain Java version.

There are two values you will want to keep track of. The source version and the target version. The source version tells what version your source code is written in. Whereas the target version tells what version of Java you want your class files in.

If for instance you have a project written in Java 1.4 source style, but you have to run it on a Java 5 you’d set the source version to 1.4 and the target to 1.5. You are now compiling Java 1.4 source into Java 5 class files.  Unfortunately you’re not able to do the opposite, compile Java 5 source code into Java 1.4 class files.  This is probably due to API incompatibilities, Java 5 has a larger API than Java 1.4.

Now, in Eclipse you have two settings in three places that controls the source and target versions of your compilations. Under Window->Preferences->Java->Compiler (Eclipse 3.4) you’re able to set the versions for the whole IDE.

When you create a new project you’re able to determine what version of Java (source and target you want) and right clicking on a project and choosing Properties->Java Compiler, you have the same dialog as before.

You set the target level in the select box “Compiler compliance level”, and optionally by unchecking the “Use default compliance settings” you’re able to change the target (“Generated .class files compatibility”) and source respectively.

If you experience other problems you may want to “clean” your project(s). Cleaning a project means all compiled files are removed and all source files are recompiled (something the IDE will do by itself when you change compilation versions, but if you want to be sure, you can do it manually). This is done by choosing Project->Clean. In the dialog you can chose to clean all projects or just those you select.

Has the Large Hadron Collider destroyed the world yet?

You may have heard of the Large Hadron Collider or perhaps concerns about its safety, and if not you may still have come across this funny web page to test if it has destroyed the world yet.

Check the source for the last one as well, there are a few laughs. Their test to see if the world has ended is:

if (!(typeof worldHasEnded == "undefined")) {
    document.write("YUP.");
} else {
    document.write("NOPE.");
}

If the undefined variable worldHasEnded is not “undefined” then there’s some really spooky stuff going on… like the end of the world… otherwise we’re all safe and sound. In the same spirit I’m offering a test for world destruction for Java (and possibly C++ and other object oriented languages as well):

System.out.print("Has the Large Hadron Collider destroyed the world yet? ");
if (this == null) {
    System.out.println("Yes!");
}
else {
    System.out.println("Nope");
}

Is the object running this test not existing any more… then risk is neither is the rest of the world…

Of course, we’ll have to wait until sometime in the end of October or beginning of November before they actually start colliding protons… and then perhaps the world will end…

Iterating a list, and deleting from it, Java vs .NET

Or how I came to realize I could live a life time without .NET and be just as happy.

I’m just fresh from having tried to iterate a list… and delete items from it while iterating.  In .NET with C#.

It turns out a statement like:

void deleteFromList(IList<X> list) {
     foreach (X x in list) {
        if (x.DeleteMe) {
            list.Remove(x);
        }
    }
}

Will throw an InvalidOperationException stating you cannot perform a foreach and delete at the same time.  This is actually not that big of a surprise, or it shouldn’t be…  the same happens in Java if you delete and iterate at the same time.

This is how I would have done this in Java:

void deleteFromList(List<X> list) {
     Iterator<X> itr = list.iterator();
     while (itr.hasNext()) {
	X x = itr.next();
        if (x.DeleteMe) {
            itr.remove();
        }
    }
}

It’s simple, clean and it does not throw exceptions. If you believe the code may be run asynchronously, slap on a “synchronized” and you’re home safe.

So, how to do this with .NET?  Well, you can’t use Enumerators (which are the .NET “equivalent” of iterators), they don’t have a remove method.  Further worse, if you are unlucky enough to run version 1.1 your only option seems to be some unholy concoction like:

void deleteFromList(IList<X> list) {
    IList<X> toBeDeleted = new List<X>();

    foreach (X x in list) {
        if (x.DeleteMe) {
            toBeDeleted.Add(x);
        }
    }

    foreach (X x in toBeDeleted) {
        list.Remove(x);
    }
}

Don’t even start a conversation on synchronization with this mixup.  Anyway, those who are “lucky” enough to code .NET 2.0 can do something like:

myList.RemoveAll(delegate(X x) { return x.DeleteMe; });

Now, if you’d like to base the “DeleteMe” calculation on some external paramter like input to the deleteFromList method or if you’d like to do more than just delete x you’ll have to experiment, it’s probably possible… with a solution like the double lists above perhaps?

Regardless.  Someone said it was old news to be a Java programmer, I can only guess because of the lower hour wastage when you program Java systems, which in turn means lower bills to the clients and finally lower wages to the programmers.

It costs to be on top…

Programming booleans

When looking at other programmer’s code I’m sometimes surprised with things like this:

exportDocumentView(java.lang.String absPath, java.io.OutputStream out,
boolean skipBinary, boolean noRecurse)

And in such prominent frameworks as Java Content Repository as well.

What’s my problem then? Double negations. In order to do exportDocumentView and get binary data and recursive export you’ll need to do:

exportDocumentView(“/path/to/my/Node/”, System.out, false, false)

Sure I can handle it… but… false to opt something in? I find it rather fishy. Call me an idiot but my brain just don’t deal with that kind of stuff easily…

What I would have wanted instead was:

exportDocumentView(java.lang.String absPath, java.io.OutputStream out,
boolean includeBinary, boolean recursive)

Which would have been called like:

exportDocumentView(“/path/to/my/Node/”, System.out, true, true)

For when we want binary data and recursive export, and like this for the case when we don’t want either or both:

exportDocumentView(“/path/to/my/Node/”, System.out, false, true)
exportDocumentView(“/path/to/my/Node/”, System.out, true, false)
exportDocumentView(“/path/to/my/Node/”, System.out, false, false)

I’m just saying. In my world false means “no” and “no” means don’t give me something or don’t do something:

“Don’t return binary data.”
“Don’t recurse the tree of nodes.”

To be compared with:

“Don’t skip binary data.”
“Don’t do no recursing.”

(But you’re free to curse? :o)