Tag Archive for 'java'

Test your Java experience for free – JavaBlackBelt

Recently I’ve come across another very interesting social service – JavaBlackBelt. Basically it gathers programmers who use Java language and related frameworks and aspects (OO programming, JSP, Struts, JSF, EJB). There are even exams on C#, Ruby, JavaScript, and AJAX but some of them are still beta versions.

Of course I’ve taken a couple of exams and this is my current JavaBlackBelt rank:


You can also have a look at my JavaBlackBelt profile.

It’s a pity I discovered JavaBlackBelt only after passing the Sun Certified Java Programmer (SCJP). However it’s a good practice to refresh Java topics even though I haven’t been using that language in business for a year already…

 Test your Java experience for free   JavaBlackBelt

GlassFish Training Offer

For a long time I haven’t written a word here… The main reason is I was moved to a new project and am so busy I simply don’t have time to describe solutions to problems I’ve been facing. This project is again not Java based – .Net.

To be honest, I haven’t written anything serious in Java for almost a year! And my last work in Java EE was at the end of university times (even the name was different – it was J2EE then!). Maybe that’s why GlassFish Training Offer by Sun sounded so attractive, even more because there are a few training courses available at that link totally for free!.

Just to refresh my knowledge around Java EE I went through course titled GlassFish Application Server: Introduction (WMT-SAS-1536). It took c.a. an hour to complete it by reading slides and listening to Text-To-Speech lecture. All in all it was quite funny to ‘take part’ in a course at home, in the evening, sitting in the armchair next to my wife watching a movie icon smile GlassFish Training Offer

img 0635 262x350 GlassFish Training Offer

Course attendee icon smile GlassFish Training Offer

Should you have some free time and a little of willingness to learn, I advise going to GlassFish Training Offer by Sun, learning how to register to attend free courses, and doing it yourself!

Sun Certified Java Programmer – finally

Time went fast since my declaration. I didn’t have much time and willigness to study but I gained them recently and finally did it: from today morning I’m a Sun Certified Java Programmer. The score: 94%.

If you’re planning to take it too, I wish you luck.

Tricky example with polymorphism

Example

Can you predict the output of the following code?

class SubTest extends Test {
    public int aNumber;

    public SubTest() {
        aNumber = 17;
    }

    public void doubleANumber() {
        System.out.println("Inside SubTest.doubleANumber()");
        aNumber *= 2;
    }
}

public class Test {
    public int aNumber;

    public Test() {
        aNumber = 6;
    }

    public void doubleANumber() {
        System.out.println("Inside Test.doubleANumber()");
        aNumber *= 2;
    }

    public static void main(String[] args) {
        Test t = new SubTest();
        t.doubleANumber();
        System.out.println("The value of aNumber is " + t.aNumber);
    }
}

Result

The output is:
Inside SubTest.doubleANumber()
The value of aNumber is 6

As you see, it was not the reference type but the real object type of t variable that decided which method was invoked at runtime. This way, aNumber of SubTest class was modified. This variable shadowed aNumber of Test class. Therefore, Test.aNumber variable was untouched (didn’t change at all).

Threads: multiple call to run() method

You can call run() method of a thread many times. However, not a single new thread will be started. This way JVM will only execute the code from run() method. And this will not probably be what you tried to achieve.

Remember: to start a new thread, you need to call start() method, which among others, will execute run() method in a new concurrent context.

java.util.IllegalFormatConversionException when using System.out.format()

A few weeks ago I described how to format output using System.out.printl() and System.out.println() methods

Try to run the code below:

double avgAge = 245 / 34;  
System.out.format("Average age is %d.", avgAge);

Without doubts you’ll get an exception thrown at runtime:

Average age is Exception in thread "main" 
java.util.IllegalFormatConversionException: 
d != java.lang.Double
    at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
    at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
    at java.util.Formatter$FormatSpecifier.print(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.io.PrintStream.format(Unknown Source)

The reason is becase wrong conversion label was used. To recall, conversion label is ‘%’ sign followed by a letter b, c, d, f, or s inside System.out.format().

In the above example, %d meant that an integral type (byte, Byte, short, Short, int, Integer, long, Long, BigInteger) would be used. However, finally there was a floating point passed (avgAge). This example would work if this conversion label were used: %f.

So, remember to be careful with conversion label!

What happens if concate String value and int?

Can you predict the output/result of the following code?

String s = "A String ";
s += 12345;
System.out.print(s);

The answer is: “A String 12345“.

The reason for that is described in the desciption of String class in Java 2 Platform SE 5.0 API:

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.

Unreachable catch block

Always contruct try-catch blocks in a way that assumes catching Exceptions from more detailed to more generic.

Example

try {
    String [] tab = null;
    System.out.println(tab[3]);
} catch (Exception e) {
    System.out.println("Exception");
} catch (NullPointerException e) {
    System.out.println("NullPointerException");
}

The above presented snippet will cause compilation error:

Unreachable catch block for NullPointerException. It is already handled by the catch block for Exception

Solution

try {
    String [] tab = null;
    System.out.println(tab[3]);
} catch (NullPointerException e) {
    System.out.println("NullPointerException");
} catch (Exception e) {
    System.out.println("Exception");
}

This way, if you invoke this snippet you’ll get the following output on the screen: “NullPointerException”.

What if you extend an abstract class and implement an interface when both define a method with the same name?

Imagine you need to implement a class that extends an abstract class and implements an interface when both define a method with the same name – test().

Example

interface Implementable { public void test(); }
abstract class Superclass { public abstract void test(); }

public class Test extends Superclass implements Implementable {
    /* definition of load method(s)..... */
}

The following will not compile, getting (among others) duplicate method test() error:

interface Implementable { public void test(); }
abstract class Superclass { public abstract void test(); }

public class Test extends Superclass implements Implementable {
    public void Superclass.test() { }
    public void Implementable.test() { }
}

Solution

The correct implementation looks as follows:

interface Implementable { public void test(); }
abstract class Superclass { public abstract void test(); }

public class Test extends Superclass implements Implementable {
    public void test() { }
}

In such case, you need to define the body of test() method ONLY ONCE.

Java vs. C#

From now on I’ll be doing much more in Microsoft .NET rather than in Java. Thus, it seems my preparation for SCJP exam will slow down now… Also, I presume there’ll be slightly less about Java on that blog from now on (at least for some time).

I learned about .NET framework and C# programming language at the univesity, but it was a few years ago. Also, I’ve never been involved in a business project that used this framework. So, time to refresh the knowledge of .NET icon smile Java vs. C#

Luckily, it seems there shouldn’t be much difficulties in switching from Java to C#. Of course, those languages differ but still they have a lot in common. This article should be helpful in understanding the differences between Java and C#. It’s well written and the theory is supported with code examples.

After refreshing C# there will be time to re-learn ASP.NET…