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);
}
}
}