SARAVANAN SIVAJI

Dedicated to JAVA Technologies

Archive for March, 2009

Globally Unique Package Names in JAVA

Posted by SARAVANAN SIVAJI on March 7, 2009

One of the important functions of packages is to partition the Java namespace and prevent name collisions between classes. It is only their package names that keep the java.util.List and java.awt.List classes distinct, for example. In order for this to work, however, package names must themselves be distinct. As the developer of Java, Sun controls all package names that begin with java, javax, and sun.

For the rest of us, Sun proposes a package-naming scheme, which, if followed correctly, guarantees globally unique package names. The scheme is to use your Internet domain name, with its elements reversed, as the prefix for all your package names. My web site is saravananmtech.com, so all my Java packages begin with com.saravananmtech. It is up to me to decide how to partition the namespace below com.saravananmtech, but since I own that domain name, no other person or organization who is playing by the rules can define a package with the same name as any of mine.

Posted in com.saravananmtech.java | Leave a Comment »

Mutable and Immutable Objects in JAVA

Posted by SARAVANAN SIVAJI on March 7, 2009

Mutable Objects: When you have a reference to an instance of an object, the contents of that instance can be altered

Immutable Objects: When you have a reference to an instance of an object, the contents of that instance cannot be altered

To demonstrate this behaviour, we’ll use java.lang.String as the immutable class and java.awt.Point as the mutable class.

Point myPoint = new Point( 0, 0 );
System.out.println( myPoint );
myPoint.setLocation( 1.0, 0.0 );
System.out.println( myPoint );

String myString = new String( "old String" );
System.out.println( myString );
myString.replaceAll( "old", "new" );
System.out.println( myString );

In case you can’t see what the output is, here it is:

	java.awt.Point[0.0, 0.0]
	java.awt.Point[1.0, 0.0]
	old String
	old String

We are only looking at a single instance of each object, but we can see that the contents of myPoint has changed, but the contents of myString did not. To show what happens when we try to change the value of myString, we’ll extend the previous example.

String myString = new String( "old String" );
System.out.println( myString );
myString = new String( "new String" );
System.out.println( myString );

The output from this is:

	old String
	new String

Now we find that the value displayed by the myString variable has changed. We have defined immutable objects as being unable to change in value, so what is happening? Let’s extend the example again to watch the myString variable closer.

String myString = new String( "old String" );
String myCache = myString;
System.out.println( "equal: " + myString.equals( myCache ) );
System.out.println( "same:  " + ( myString == myCache ) );

myString = "not " + myString;
System.out.println( "equal: " + myString.equals( myCache ) );
System.out.println( "same:  " + ( myString == myCache ) );

The result from executing this is:

	equal: true
	same:  true
	equal: false
	same:  false

What this shows is that variable myString is referencing a new instance of the String class. The contents of the object didn’t change; we discarded the instance and changed our reference to a new one with new contents.

If you look at the example above, you can see the point I’m trying to sneak through. You can always change the value of a variable by getting your variable to reference a new object. Sometimes you can change the value of a variable by keeping a reference to the same instance, but change the contents of the instance.

After you have eliminated those possibilities, you have a variable that retains its reference to an object, but the contents of this object cannot change. Doesn’t sound like a very interesting idea, and it sounds a bit too simple to be useful.

It turns out that Immutable Objects, that is objects that you cannot change the contents after they have been set, are a very handy tool when used in the right place. They can promote thread safety in your code, you can share them around without being afraid that they will change without your knowledge, they are great for caching and constants. But we’re not going to cover any of that yet; we are going to concentrate on building immutable objects.

Building an Immutable class

So what is it about the String class that makes it Immutable while a Point is mutable?

In this case, Strings have no mutators while Points do. If we removed all of the mutators from the Point class, would it be Immutable? No it wouldn’t. Removing mutators is a necessary first step, but immutability requires more than that to ensure that the contents of an instance never changes.

Fields must be private

Obviously all of the fields must be private. There is little point removing the mutators if they aren’t even required to change the instance contents.

public class ImmutablePoint
	{
		//note there are no mutators!
		private double x;
		private double y;

		//and the rest...

This is almost enough, but there are two more steps to consider.

Make sure methods can’t be overridden.

If your class gets extended, it could add extra fields that are not immutable, or the methods could be overridden to return a different value each time. There are two ways to protect against this.

The preferred way is to make the class final. This is sometimes referred to as “Strong Immutability”. It prevents anyone from extending your class and accidentally or deliberately making it mutable.

The second way, also called “Weak Immutability” is to make your methods final. It allows others to extend your class to add more behaviour, but protects the original contract specified by the class. If you want a more verbose description, imagine a class A is weakly immutable. If you have an instance of object A, it is immutable. If someone creates class B that extends A, it is only the behaviour defined by the A class that is immutable. Any added behaviour from class B may not be immutable.

Protect mutable fields

The last requirement which many people fall victim too, is to build your immutable class from primitive types or immutable fields, otherwise you have to protect mutable fields from manipulation. To highlight this problem, we’ll use the example of a supposedly immutable class representing a person. Our class has a first and last name, as well as a date of birth.

	import java.util.Date;
	public final class BrokenPerson
	{
		private String firstName;
		private String lastName;
		private Date dob;

		public BrokenPerson( String firstName,
		  String lastName, Date dob)
		{
			this.firstName = firstName;
			this.lastName = lastName;
			this.dob = dob;
		}

		public String getFirstName()
		{
			return this.firstName;
		}
		public String getLastName()
		{
			return this.lastName;
		}
		public Date getDOB()
		{
			return this.dob;
		}
	}

This all looks fine, until someone uses it like this:

Date myDate = new Date();
BrokenPerson myPerson = new BrokenPerson( "David", "O'Meara", myDate );
System.out.println( myPerson.getDOB() );
myDate.setMonth( myDate.getMonth() + 1 );
System.out.println( myPerson.getDOB() );

Depending on the dates entered, the output could be something like this:

	Mon Mar 24 21:34:16 GMT+08:00 2003
	Thu Apr 24 21:34:16 GMT+08:00 2003

The Date object is mutable, and the myPerson variable is referencing the same instance of the Date object as the myDate variable. When myDate changes the instance it is referencing, the myPerson instance changes too. It isn’t immutable! We can defend against this by taking a copy of the of the Date instance when it is passed in rather than trusting the reference to the instance we are given.

import java.util.Date;
	public final class BetterPerson
	{
		private String firstName;
		private String lastName;
		private Date dob;

		public BetterPerson( String firstName,
		  String lastName, Date dob)
		{
			this.firstName = firstName;
			this.lastName = lastName;
			this.dob = new Date( dob.getTime() );
		}
		//etc...

Now we’re close, but we’re still not quite there. Our class is still open to abuse.

BetterPerson myPerson = new BetterPerson( "David", "O'Meara", new Date() );
System.out.println( myPerson.getDOB() );
Date myDate = myPerson.getDOB();
myDate.setMonth( myDate.getMonth() + 1 );
System.out.println( myPerson.getDOB() );

We see here that taking a copy on the way in wasn’t enough; we also need to prevent anyone from getting a reference to our mutable Date field when we pass it out.

public Date getDOB()
	{
		return new Date( this.dob.getTime() );
	}

The only point to add is that when you copy the instance on the way in and the way out, you need to make a deep copy. Otherwise you run the risk of leaving some mutable data in your immutable class!

If you are confused about the need to provide a deep copy, keep in mind that a single piece of shared mutable data, no matter how deep it is buried inside an object, makes your class mutable. When you create a copy of an object to defend against the value changing, you need to make sure your copy doesn’t include this shared mutable class. You need to copy any mutable objects all the way down to the last field, and copy any nested fields until you have a completely new copy of your own. It’s the only way to be safe!

Our Template for Immutable Classes

Now we have a template for creating immutable objects.

  • Make all fields private
  • Don’t provide mutators
  • Ensure that methods can’t be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability)
  • If a field isn’t primitive or immutable, make a deep clone on the way in and the way out.

Which classes are Immutable?

To finish up, lets discuss the common Java classes that are immutable and those that aren’t. Firstly, all of the java.lang package wrapper classes are immutable: Boolean, Byte, Character, Double, Float, Integer, Long, Short, String.

As in the Person classes we discussed, java.util.Date objects are not immutable. The classes java.math.BigInteger and BigDecimal are not immutable either, although maybe they should have been.

Posted in Uncategorized | Leave a Comment »

Sample SCJP Questions 1

Posted by SARAVANAN SIVAJI on March 1, 2009

1) Which code determines the int value foo closest to a double value bar

a. Int foo = (int) Math.ceil(bar);

b. Int foo = (int) Math.round(bar);

c. Int foo = (int) Math.max(bar);

d. Int foo = (int) Math.floor(bar);

——————————————————————–

2) Which two interfaces provide the capability to store objects using a key-value pair? (Choose Two)

a. Java.util.Set

b. Java.util.StoredSet

c. Java.util.Map

d. Java.util.Collection

——————————————————————–

3) Which two demonstrate encapsulation of data? (Choose Two)

a. Methods provide for access and modification of data.

b. Member data can be modified directly.

c. Member data have no access modifiers.

d. The access modifier to member data is private.

——————————————————————–

4) Given:

1. public class MethodOver {

2. private int x, y;

3. private float z;

4. public void setVar(int a, int b, float c){

5. x = a;

6. y = b;

7. z = c;

8. }

9. }

Which two overload the setVar method? (Choose Two) (2 correct answers)

a. public void setVar(int a, float c, int b) { setVar(a, b, c); }

b. public void setVar(int a, float c, int b) { this(a, b, c); }

c. public void setVar(int a, float b){ x = a; z = b; }

d. void setVar (int a, int b, float c){ x = a; y = b; z = c; }

——————————————————————–

5) Which statements about static inner classes are true? (Choose Two) (2 correct answers)

a. A static inner class has no reference to an instance of the enclosing class.

b. Static members of a static inner class can be referenced using the class name of the static inner class.

c. A static inner class requires an instance of the enclosing class.

d. A static inner class requires a static initializer.

——————————————————————–

for answers, visit

Posted in Uncategorized | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.