Studying for SCJP?

I was recently quizzed about prep for the Sun Certified Java Programmer exam, so here’s a quick rundown of the resources I found useful and tips I picked up when I was studying for SCJP 5. All in, it cost me around £200 and took just under four months. I can recommend the following resources:

  • SCJP 5 Study Guide by Kathy Sierra and Bert Bates. Choose the book for the certification version you’re going for. Work through every chapter and make sure you understand every concept and gain some familiarity with the APIs. I found flash-cards (little cards, questions on one side, answers on the other) invaluable for really burning some of the more difficult to remember stuff. As I didn’t have a programming or Computer Science background, I learnt more about Object-Oriented concepts and programming in the first three chapters of this book than I did from anywhere else.
  • javaranch.com SCJP FAQ for the latest thoughts info on certification, and the SCJP Certification Forum, in which you’ll start by asking questions and wind up answering the questions of others as you get lined up for the exam. The FAQ is also a good place to check what the recent exam takers are saying about the exam and the study materials. You can also use the Rules Roundups to get a feel for answering questions, although they’re pretty easy compared to the exam.
  • Mock exams. When you think you’re nearly ready for the exam, grab a pack of mock tests (I used whizlabs). I certainly wasn’t as ready as I thought I was! Do them properly – set aside at least an hour and try and work as if under exam conditions – you also get used the format of the exams and there’s a few tricky corner cases in the mock exams I did that are worth knowing about.
  • Sign up for your exam at prometric.com. I signed up for the exam as soon as I’d finished reading the Study Guide, because I’m fundamentally lazy and needed the impending deadline! If you do the same, you might want to give yourself a month or two between booking and exam day to do those mocks and deal with any gaps in your knowledge they throw up.

I’ve also got a couple of tips on techniques to use for answering some of the tricker exam questions – that can also come in useful when writing and debugging code.

First up, the exam will often have a code sample and ask you to choose from a number of options. ‘Does not Compile’ is almost always an option, and it kept catching me out at first. The way I dealt with it was to run through the sample twice – first as the compiler, looking for those errors that would prevent the code compiling in the first place. Only if that first check didn’t throw up any problems do you need to imagine the behaviour of the code as it runs and look for exceptions and results.

Second, come up with some way of sketching the changing references to objects as you work through a code sample. This’ll help you catch subtle re-assignments you might miss working it through mentally.

It’ll take up your time. I was probably spending about 5-10 hours a week learning, revising and writing code for those four months – that counts when you’re working full time. It’s worth it though, particularly if you’re an inexperienced Java programmer. It’ll make you aware of some of the principles and practises you should be thinking about and it’ll give you something of a guided tour of the core Java APIs.

If you going to go for this cert, good luck!

Advertisement

When Eclipse Plugins Don’t

Quick Version

If, after ‘installing’ a plugin for Eclipse 3.4 it’s not visible in Preferences or in context menus, check that your user account has permissions to write into the appropriate Eclipse directories – because Eclipse doesn’t warn you.

Preamble

For those who don’t know, Eclipse is an IDE heavily used for Java development. Like anything else, it’s a delicate balance of awesome and suckage, and today I got caught out by a pinch of suckage.

It’s a plugin-based platform, which means that anyone can write a piece of software that ‘plugs-in’ to Eclipse to extend or enhance the functionality. It’s a great approach, allowing me to tailor my own installation to my needs. Having recently re-installed Ubuntu Linux, earlier today I was trying to set up my plugins without success.

The Problem

I set up the m2eclipse update site as described in the documentation (pretty standard fare… Help > Install New Software…, paste in the update site URL and choose components to install) but after ‘installation’ was completed there was no sign of the plugin. There should have been new options appearing all over Eclipse, but no. Tumbleweed.

Tried installing the next plugin on my list… Subclipse. Same story. So not a problem with a plugin…

The Solution

…and then it dawned on me. I’d installed Eclipse into /opt, which is all locked down to root, with administrative privileges. Schoolboy error – no permissions for the plugin files to actually be installed under the authority of my user account, which is the context that Eclipse normally runs.

A quick chown to root:admin for the /opt/eclipse directory (rather heavy handed – I should probably have worked out which directories I needed write access to, but I was out of patience), ‘uninstalled’ the plugin in the Eclipse, tried the install again and then I was back in business.

I’m really surprised that Eclipse doesn’t complain when it’s ‘installing’ a plugin in directories to which it has no access. I may not be the sharpest tool in the box, but I’m fairly sure that permissions problems happen to other people too. I might go so far as to find out where you feed back to the Eclipse development community for once. Anyways, this post will help remind me next time I get this wrong, it might help someone out, and if nothing else you might be mildly entertained by my ineptitude.

Perl is slower and faster than Java

Bit of a random one coming up…

I needed to get an measure of the difference in performance between Perl and Java for a simple client application, so I wrote the traditional ‘Hello World’ app in both and ran a bunch of executions averaging over the time from start to end of execution. The net result:

Perl is around 34 times faster than Java.

Really? I thought Java was supposed to be fast? In fact, Dhananjay Nene talked about how comparatively fast a selection of languages – including Java – were on his blog, and cwilbur ‘s comments suggest that in that experiment:

Java is around 100 times faster than Perl.

So how can these two conflicting results both be true? I’m sure you’ve already figured it out, but I’m going to tell you anyway.

Java code takes hundreds of milliseconds to start up, because Java code runs in the Java Virtual Machine which needs a little time to get itself ready before your code can run. Once it’s up, however, you can get performance close to (or even better than, in reality) that of typical C++. [edit – originally no supporting evidence was offered. My sources for this statement on Java vs. C++ are resources like http://scribblethink.org/Computer/javaCbenchmark.html like https://www.theserverside.com/opinion/Is-Java-slow-Compared-to-C-its-faster-than-you-think. Personally, I have very limited hobbyist experience of C and C++ many years out of date now]

On the other hand, Perl doesn’t need that environment and so can start faster but trades off more overhead at runtime, meaning slower running performance.

Just goes to show, application performance is another area where there’s no one right answer – it’s about choosing the right tool for the job – I don’t think there’s any way round these performance characteristics without cheating.

Why Java?

I was recently asked, why Java? It’s a great question – exactly why do I choose to learn the Java language?

I gave it some thought and I’ll share what I considered. I’m certainly not saying that what follows is a justification of the Java language in any general context, nor am I any kind of expert. This is just my view, given my circumstances.

It’s Free!

If you want to learn a language you don’t want to be laying out pots of cash up front. It’s likely you’ve got a Java Virtual Machine on your computer right now, and obtaining a development kit to get you started writing software is free and straightforward. Win.

The Java Virtual Machine

You never know when you might need to run that little app you wrote on a Windows host, or a different flavour of UNIX, or even a big ol’ IBM mainframe system – it’s nice to have some confidence that it’s just going to work.

Now, the JVM runs on any platform I can think of. Perhaps in the early days, there was some divergence in different platform implementations of Java (having felt the pain of the slight non-standard nature of the Micro$oft JVM in IE some time ago!) which somewhat hampered the cross-platform claim, these days there’s a suite of compliance tests that a JVM implementation must pass to brand itself Java compatible. That means that I don’t have to worry too much about cross-platform compatibility.

The JVM supports more than just the Java language. Jython, JRuby, Scala, JavaFX, Groovy, Fortress, Clojure… the list is getting ever longer, and there’s even a JVM Languages Summit. So, if you’re using the Java language and find a problem that better solved in another language, it’s perhaps not such a huge leap to get your Java code and your new JRuby code working together. Tim Bray wrote up some nice notes on the language summit here if you’re looking for a little more.

The other trick about the JVM is that your code gets better without you changing it. As new JVMs are released, they include the latest, hottest optimizations that take the software you write and give it go-faster stripes.

Tools and Platforms

Tool support for the Java language is extensive enough that there is generally a choice – for example, there is a choice of many Integrated Development Environments (Eclipse, NetBeans, IntelliJ IDEA to name but three) in which to write your software.

If you’re building ‘Enterprise’ software (whatever that really means!) you have a choice of application servers (WebSphere, JBoss, Jetty, Tomcat, GlassFish…) that all implement the Java Enterprise Edition specification in whole or in part (for example, the open source Tomcat application server supports a stripped-down subset of the spec) you know that any of the application servers should run your software.

With all these things the choices mean that I can choose the implementation with the right strengths and at the right price point for the project in hand.

Learning

Java’s got a lot going for it as a learning language – it seems to be on the syllabus for most computer science degrees. There’s a wealth of online material available for free, including Sun’s own learning trails and Sang Shin’s excellent javapassion.com learning site.

I know that the question of value in professional certification seems to polarize opinion, but there certainly is a certification trail in the Java language that’s not trivial to achieve.

The cost of achieving these certifications is financially quite insignificant, but (certainly for me – I’m sure there’s folks that find this stuff easier) demands a significant amount of time and commitment. The objectives and exam questions are put together by teams of Sun engineers, Java developers and Java instructors, orchestrated by Sun. (Thanks to Bert Bates and javaranch.com for that info!)

Having done a couple of certs myself, I found them to be a very useful useful guided tour of the language and its extensions. I found plenty of useful features and techniques whilst studying that have since steered me clear of errors and wasted time.

The JCP and Standards

New APIs for the Java language happen through the JCP, or Java Community Process. Everyone from from individuals to the largest IT players (IBM, Cisco Systems, Nokia – the members are listed here) are involved, and new standards happen in a publicly visible process of proposal and review.

Don’t believe me? Here’s the latest Java Enterprise Edition spec. See those JSR numbers? They’re the specifications that have been developed, reviewed and approved as part of the JCP.

Libraries

There’s sometimes so much choice of open source Java libraries, it’s hard to know what to choose for a given problem. The Apache Software Foundation hosts loads of open source Java projects, as does Google Code and java.net.

Not that every library is a piece of awesome… but many are. Having lots of choice increases the chances there’ll be something out there that’s already been built and tested and fits the bill. The libraries and APIs I have to use with my language of choice to get things done make a big impact to my productivity.

What – No Discussion of Technical Stuff?

Nope. I reckon it’s rather pointless to try and discuss differences between the capabilities of one language versus another. Anything computable can be computed in any Turing-complete language, which I think covers any language you might seriously approach as a general purpose problem solving platform.

So it’s not about what can or can’t be done – it’s really about what language I can be most effective and productive in. The biggest productivity killer in Java seems to be the boilerplate code necessary to do simple things, but over the last couple of years, strides forward have been made with annotations, for example, to reduce the boilerplate problem.

That’s All Folks

That’s about it, really. There’s plenty of other languages that can lay claim to some of the points I’ve made, but few that can claim them all.

There are other languages I choose for specific jobs (JavaScript for client-side behaviour in web browsers, PERL for sysadmin-type scripts) but my day to day workhorse, and the focus of my learning attention, is Java. For now, at least.

If I’ve missed anything or you disagree, feel free to drop me a comment!

When Disabling DNS Caching Doesn’t

If you’re going to fiddle with networkaddress.cache.ttl, do it before you touch the network.

I was using the java.net.InetAddress class to resolve IP addresses from DNS names the other day.

I wanted to test my code by manipulating my local system’s ‘hosts’ file, to quickly simulate moving IP addresses around behind a DNS name, so I also set disabled caching the resolved addresses from one call to the next by programmatically setting the networkaddress.cache.ttl Security property to ‘0’. According to the javadocs,

The value [assigned to networkaddress.cache.ttl] is specified as as integer to indicate the number of seconds to cache the successful lookup.

which is true, and everything was peachy – my hosts file changes were immediately picked up.

At first.

I continued to build my code and all of a sudden, the caching came back and the changes I was making in my hosts file were ignored.

By backtracking my changes, I worked out that the breaking change happened when I executed a network call which involved name resolution BEFORE I disabled the cache.

I moved the setting of the property to happen before I touched the network et voila – everything peachy again.

This (feature|problem|bug) is documented in a couple of places when you know what you’re looking for, like here.

And here’s a simple code demo of it in action:

public static void main(String[] args) throws Exception {
  String name = "google.com";

  //lookup(name);

  Security.setProperty("networkaddress.cache.ttl", "0");
  while (true) {
    lookup("google.com");
    Thread.sleep(1000);
  }

  public static void lookup(String name) throws Exception {
    System.out.println(name + ":" + InetAddress.getByName(name).getHostAddress());
  }
}

Running the sample above as-is:
google.com:74.125.127.100
google.com:74.125.67.100
google.com:74.125.127.100
google.com:74.125.67.100
google.com:74.125.127.100

But uncomment the first call to lookup(), and
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100

Cheers,

Running Apache MyFaces on Tomcat 5.5.x and below

I’ve recently been looking at JavaServer Faces (specifically Apache’s MyFaces), playing about on my home Tomcat 5.5.27 installation, using Maven2 to do my dependency management, builds etc…

…largely unsuccessfully. I just could not get the darned example app to start, with exceptions along the lines of:

20-Apr-2009 22:27:04 org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.apache.myfaces.webapp.StartupServletContextListener
java.lang.NoClassDefFoundError: javax/el/ExpressionFactory
at org.apache.myfaces.webapp.StartupServletContextListener.getFacesInitializer…

appearing in the tomcat localhost log files.
Continue reading “Running Apache MyFaces on Tomcat 5.5.x and below”

Faster Java – Strings

If you’re building a long String in Java, don’t stick String objects together using ‘+’, for example:

String str = "Hello";
str = str + world;
str = str + "!";

Why not?

It’s really slow when you do it a lot!

What should you do instead?

Use the append(String) method in StringBuffer (Java 1.4.2 on), or StringBuilder (Java 5 on). StringBuilder is slightly faster than StringBuffer, but is not thread safe. Both are much faster than concatenating String objects – by orders of magnitude. For example:

StringBuffer str = new StringBuffer("Hello");
str.append(world);
str.append("!");

Continue reading “Faster Java – Strings”