Friday, August 27, 2010

Utility methods of wrapper classes.

Wrapper classes basically have two purposes: to wrap a primitive and to provide a set of utility functions dealing with some conversions. In this article I will focus on the latter objective.

The first function that I will cover here is a static valueOf() method. It takes as an argument a string and converts it to the desired wrapper object. In most cases you can also provide a second parameter that is an int radix which indicates the base of the first parameter. The valueOf() method is provided in most of the wrapper classes (except Character). It throws a NumberFormatException (it is not checked so you don't have to declare it) if the string provided can't be converted. Here are some legal uses of it:
Integer i1 = Integer.valueOf("3");
Integer i2 = Integer.valueOf(123);
Float f = Float.valueOf("2.2");

The second method is xxxValue() where in the place of xxx we can put any primitive. This function converts the value of a wrapped object to a primitive. The following code shows a few examples of how we should use it:
Float f = Float.valueOf("5.5");
byte b = f.byteValue();
short s = f.shortValue();
double d = f.doubleValue();

The next function that is important to remember is parseXXX(). It is static and takes a string as an argument and parses it into an appropriate primitive. It also throws NumberFormatException in case when the string arument is not well formated. Let's have a look at the following demonstration code:
double d = Double.parseDouble("123.456");
int i = Integer.parseInt("345");
byte b = Byte.parseByte("127");

And that's it! Three useful and important methods that we should know for the exam!

Wednesday, August 25, 2010

No more Sun Certified Java Programmer!

Erm... nearly. If you want to become one you should simply hurry up. You have 7 days for that and starting on 1st September you will be named Oracle Certified Professional Java SE 6 Programmer. That's another outcome of the acquisition Sun by Oracle that has had place at the beginning of this year.

As for me the name of the certificate doesn't really matter but what actually pops up in my mind is the question whether and when the employers will become familiar with the new name. Let's be honest - one of the reasons of why we become certified is the fact that it adds a new valuable element to our CV. But for this, the potential employer must be familiar with the title. Recently I read on a forum that Oracle sends some newsletters about the naming changes for the interested people (you probably need an account in the Oracle's Education Center) but for sure it will take some time to spread the word.

Nevertheless, below is the link to Oracle's website with additional information and names of the other exams. Yes! All the names has been changed!

Oracle Certification Program

Friday, August 20, 2010

Assignments.

By the title I actually mean the 3rd chapter of the K&B SCJP book. I have to admit that it was really surprising. I have learnt many new things that I was completly unaware of. Of course, in the real projects, when you use some IDE it's nearly impossible to make mistakes of this sort but on the exam they can be very savage. So below you will find some important points from this chapter that you really should pay attention to, during the exam.

First, we'll talk about the literals. Remember that every integer literal is an int. So there is no problem if we want to do the following assignments:
int a = 5; (fits well)
long b = 6; (fits well since long is bigger than int)
but what if we try to assign the integer literal (so an int) to the smaller type? Let's have a look!
byte c = 7;
And yeah, there is still no problem. That's of course good for us but basing on the above that shouldn't work. Well, that happens because the compiler makes an implicit cast so in fact, it looks like this:
byte c = (byte)7;
Alright. That's very convenient for us. But this implicit cast is applied only to literals! So this is not going to work:
int a = 5;
byte b = a;
To compile the code consisting of the above assignments you need to do an explicit cast:
int a = 5;
byte b = (byte)a;
Also keep in mind the following rule. The result of any expression involving an int or anything smaller, like byte and short will result in an int! So the following will... not compile!
byte a = 5;
byte b = 1;
byte c = a + b;
You need to put an explicit cast! One more thing about the floating points literals. They are always doubles. And here the compiler won't make an implicit cast, the following code will not compile:
float d = 2.5;
Instead you should write:
float d = (float)2.5;
Or mark that what you mean is really a float by adding and f or F at the end of the literal:\
float d = 2.5f;
Ok, that's it for the literals! Now let's move on to the primitive casting.
First of all, it's important to remember that the implicit cast happens when we assing a smaller to a bigger. So for instance:
int a = 5;
byte b = (byte)a;
long c = 'a' + 'b';

a = b;
c = a;
c = b;
These are all legal assignments. But the followings are not:
b = a;
b = c;
a = c;
And what do we need? An explicit cast!
b = (byte)a;
b = (byte)c;
a = (int)c;
Et voila monsieur! Also the same thing happens with floating points. All the following are legal:
double d = 2.5;
float f = 3.4f;
int i = 12;
long l = 45;

d = l; // assigning long to double
d = f; // assigning float to double
f = i; // assigning integer to float
But in case when a truncation may occur we have to make an explicit cast otherwise our code will produce an error.
The followings are legal but the cast is necessary:
double d = 2.5;
float f = 3.4f;
int i = 12;
long l = 45;

f = (float)d;
i = (int)f;
l = (long)d;
That's a piece of cake but I'm sure that you've found here something new and interesting for you!

Thursday, August 19, 2010

Downcasting and a compiler.

Today I will write shortly about the downcasting and especially about the way the compiler can assist us while doing this. Actually it can't do a lot. It trusts us when we do the downcast that it is actually possible. Let's consider this example:
 class Vehicle {}
class Car extends Vehicle {}
public class Sfield {
public static void main(String[] args) {
Vehicle v = new Vehicle();
Car c = (Car)v;
}
}

This example compiles without any problem. But what will happen is... a java.lang.ClassCastException thrown! However there is one situation, when the compiler can help us. If we try to downcast the class from the different inheritance tree the compiler will let us know about it during the compilation time and not the runtime! For instance:
 class Vehicle {}
class Car extends Vehicle {}
public class Sfield {
public static void main(String[] args) {
String v = new String("Vehicle");
Car c = (Car)v;
}
}

So if the compiler knows that the downcast will not work for sure it will manifest it with:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot cast from String to Car
But in the first example it might happen that the v references to the Car object. But it was not possible to verify this at the compilation time.

Monday, August 16, 2010

Inheritance and the default superclass constructor.

In this short article I will write about the situation, when we extend some class but its default constructor is not accesible for us. For example it has a private modifier or a default one and we are in a different package. If this is a case, we have to remember to use another (accessible) superclass constructor in our subclass constructor. If we don't do it, a compiler will try to insert a call to the default constructor super() which obviously will not work. Below is an example of this:
 class U1 {
private U1() { }
public U1(int x) { }
}
class U2 extends U1 {
U2() {
System.out.println("U2 construction...");
}
}

To mitigate the situation we should explicitly use the public but not default constructor as in the following code:
 class U1 {
private U1() { }
public U1(int x) { }
}
class U2 extends U1 {
U2() {
super(5);
System.out.println("U2 construction...");
}
}

Sunday, August 15, 2010

Static modifier.

Hello there! Static modifier is a very wide subject and obviously I'm not going to explain everything now. But you will find here a couple of interesting notes!

First of all we will talk about static variables. Remember! There is only one static variable for the whole class and all its subclasses and their instances! The following example illustrates it:
 class T1 {
static int a = 5;
}
class T2 extends T1 { }
public class Sfield {
public static void main(String[] args) {
T2.a = 6;
System.out.println(T1.a);
System.out.println(T2.a);
}
}

And the output is:
6
6
(Luckily there is no third 6 since it could have got scary)
What would happen though, if in T2 we define again the static int a? Let's have a look:
 class T1 {
static int a = 5;
}
class T2 extends T1 {
static int a = 6;
}
public class Sfield {
public static void main(String[] args) {
System.out.println(T1.a);
System.out.println(T2.a);
}
}

And the output of this will be:
5
6
So now apparently we have different static fields for each class and its instances. What does matter here, is the type of the reference variable that we try to access the member.

The similar thing happens with static methods. It is important to remember that static methods can not be overridden. We can though, redefine them!
 class R1 {
static void say() {
System.out.println("R1");
}
}
class R2 extends R1 {
static void say() {
System.out.println("R2");
}
}
public class Sfield {
public static void main(String[] args) {
R1.say();
R2.say();
}
}

And the output will be:
R1
R2
But still it's not an override but a redefinition!

Thursday, August 12, 2010

Enumerate it!

Today I will write about really cool thing in Java that is enum type. If you used to code in C/C++ you may wonder what is so cool about it since it's really simple and straightforward. Well, in Java things are a little bit different. Of course, you can use enums in the way that you know from C, for example:
 enum Colour {RED, YELLOW, BLUE}

but that's not really what I'm gonna cover here. Enums in Java are much more than that. They are some kind of a class so you can actually add constructors, instance variables, methods and one more thingy.
Let's say that you would like somehow associate the enum value with a string that says something more about the colour. We can do it in this way:
 enum Colour {
RED("bloody"), YELLOW("shiny"), BLUE("sea");
String info;
Colour(String info) {
this.info = info;
}
}
public class Woo {
public static void main(String[] args) {
for(Colour c: Colour.values()) {
System.out.println(c.info + " " + c);
}
}
}

So in the above code we define our Colour enum. It is different from the previous example from the very beginning - we define our values but in brackets we put our additional information. This can happen because later on we define a constructor that can handle this. We also define a "info" field to which, the constructor will pass given reference. In the main() function we also use the static method of enum's values() which returns an array of previously defined enums. Please note that the order is exactly the same as in the definition.

Alright, at the beginning I mentioned some enum's features and among others there was some thingy thing. In fact, what I meant is constant specific class body. To explain it, imagine that you would like to even add some more information about the colours and that the only thing you can say more about them is "mmm..." (cause they're so good so you'd like to hoover'em) except the BLUE one. With the blue you would like to say add "extreamly". To cope with it we can define a method that will return the string consisting of "extreamly". But wait! We don't want to get the same information for all enums. In case of the BLUE we want to have "extreamly". And here comes constant specific class body where we can override the method and make it specific to the chosen enum value. The important thing here is that it can be only used for overriding the methods defined in the enum. If there is no method in the enum, you can put any in the constant specific class body.
And here is the code for the example just described:
 enum Colour {
RED("bloody"),
YELLOW("shiny"),
BLUE("sea") {
public String moreInfo() {
return "extreamly";
}
};
String info;
Colour(String info) {
this.info = info;
}
public String moreInfo() {
return "mmm...";
}
}
public class Woo {
public static void main(String[] args) {
for(Colour c: Colour.values()) {
System.out.println(c.moreInfo() + " " + c.info + " " + c);
}
}
}

Tuesday, August 10, 2010

In the protected way...

You may wonder what do I mean. No, I'm certainly not gonna write about driving a bullet proof limo or wearing this kind of vest. Protected sex? No, not really. Of course it's not like I'm supporting having unprotected sex but just not this time, ok? So, here it comes 3 2 1... protected modifier! Yes, today we will talk about the protected modifier in Java. Yeah I know, you may have expected something else, like the things I mentioned before.
So let's go! At the beginning let me recap the default (package) modifier. To use this one we don't put anything in front of the member of a class, like in the following example:
 package example;
class DefaultAccess {
int a;
}

By this the member 'a' has the package access. That means that any other class in the package 'example' (or any other that we define) can access the member 'a' by a dot operator. And it's legal only in this package. A try to access it from any other package will not work. No exceptions. No excuses.

All right, that's pretty straightforward but this article is about the protected se... protected modifier it is! Okay. A protected modifier works in the same way as a default modifier as for the dot operator. So you can access a protected member within the same package with no problem. But outside it, you can forget. Well, nearly. You can actually make some sort of magic to access a protected member in the different package. And this magic is... inheritance! Okay, not a lot of magic in it. So, what we can do to access it, is to extend the class that has a protected member and then within its methods we can work around. Let's have a look at this example:
package protectedExample;

public class Loo {
protected int a;
}

package protectedExampleDifferent;

import protectedExample.Loo;

public class Woo extends Loo{
void callWoo() {
System.out.println(a);
}
}

That's how it works. First, we extend the class with protected member and then we can access it as in the normal inheritance. But how does it look for other classes that use the Woo class. Can they access the inherited member? The answer is no. For any other class, regardless to the package (of course excluding the one that the protected member is defined in) the protected inherited member is not visible. If we extend the previous example we can get:
package protectedExampleDifferent;

import protectedExample.Loo;

public class Woo extends Loo{
void callWoo() {
System.out.println(a);
}
}

class Woo2 {
void test() {
Woo woo = new Woo();
System.out.println(woo.a);
}
}
And here it's not gonna work. Even though the member 'a' is inherited and can be used within the Woo class, it can't be accessed by the dot operator by another class.
But this is not the end! We can still extend our class Woo and guess what! The member 'a' will be inherited! Let's slightly modify the previous example again:
package protectedExampleDifferent;

import protectedExample.Loo;

public class Woo extends Loo{
void callWoo() {
System.out.println(a);
}
}

class Woo2 extends Woo {
void test() {
System.out.println(a);
}
}

That's pretty savvy but that's how it works. How useful and powerful it can be!

Sunday, August 1, 2010

A few words about classpaths.

Perfect, so here we are - classpaths. The topic that nearly every programmer had a contact with but some have very shallow knowledge about them. That's why I'll recap this subject.
All right, so what actually are the classpaths? The classpaths are the directories that 'java' and 'javac' look inside, in order to find the classes that are necessary to proceed with current operations. A note: classpaths are not the only places where 'java' and 'javac' look in. Before the standard directories of JSE are searched through.

The syntax of it is as follows:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo

And now some important things:

In the above example, the Unix syntax was used as for the path directories. In the windows we will have to use something like C:\ (or other drive) and afterwards the backslashes (\).

The next thing worth mentioning is the order. The classpaths are searched from left to right so if the class that we are looking for is both in /com/foo/bar and /com/foo2/bar then we can get different results when using this two options:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo
-classpath /com/foo2/bar:/com/foo/bar:bar/foo

Ok, now we will talk about the current directory. You see, in both of the above examples the current directory is not searched! Yes, it's not searched for the .class files! I mean, if you simply invoke 'javac' with some .java file it's no problem. But as for the .class files it's just not searched. To change it, we have to add a current directory to the classpath which is denoted by a dot (.). Here is a modified previous example:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo:.

As simple as that! Never forget to add the . if the current directory has to be searched!

Also please note that there is a distinction between absolute and relative classpaths. Absolute classpath in Unix will start with a slash and doesn't matter the directory it is used from, the effect will always be the same. In case of relative classpath the effect won't be the same since the current directory is treated as a root directory for it, so if run from the wrong directory mostly the attempt will fail due to the fact that class can't be found.

The last thing that I would like to mention about the classpaths are the JAR files. In comparison to the the class files, we have to add a name of the JAR file that we want to use. So let's say that a my.JAR file is located in /com/foo/bar. To make the actual use of it we have to modify our previous example to:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo:.:/com/foo/bar/my.JAR

That's a bunch of useful information, isn't it? Yeah, stay tuned! There will be much more in the next articles!