Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, May 6, 2009

Parameterized types and bounded wildcards

We know that parameterized types (in Java) are invariant, which implies that, for example, even though Integer is a subtype (subclass) of Number, List is not a subtype of List. Let's see how this impacts you code. Assume we have a class named Bucket declared below:

public class Bucket {
   public void add(E e){...};
   public void addAll(List list){
      for(E e : list) {
         add(e);
      }
   }
}

If you would try to do the following:

Bucket numberBucket = new Bucket();
List integers = new ArrayList();
...
numberBucket.addAll(integers);

you get the error:

The method addAll(List) in the type Bucket is not applicable for the arguments (List).

How can we get out of this? Easy, by using a bounded wildcard type:

public void addAll(List list){
   for(E e : list) {
      add(e);
   }
}

Wednesday, April 15, 2009

Constant Interfaces

A constant interface is one that contains no methods, only static final fields, each declaring a constant. Below is an example:
public interface UniversalConstants {
//Speed of light in m/s
static final int SPEED_OF_LIGHT = 299792458;

//Newtonian constant of gravitation in m^3 * kg^-1 * s^-2
static final double GRAVITATION = 6.6742867e-11;
}

There were times in the past that I've used such interfaces in classes that needed the constants. This is a poor use of interfaces. An interface serves as a type that tells you what a class that implements that interface can do with an instance of it. There is nothing of this kind when using constant interfaces. How can we avoid this? (At least) In two ways. One, define the constants inside your class, if you feel that there is a strong relationship between those constants and you class. The other way is to use a utility class that cannot be instantiated, like below:
public final class UniversalConstants {
//Speed of light in m/s
public static final int SPEED_OF_LIGHT = 299792458;

//Newtonian constant of gravitation in m^3 * kg^-1 * s^-2
public static final double GRAVITATION = 6.6742867e-11;
}

When using these constants from within your own class, you can add a static import declaration and you're done!

Sunday, March 22, 2009

Breaking information hiding in Java

Information hiding is one key feature of Java in particular, and OO in general. It is not to be confused with encapsulation, since you can bundle data with your methods and not hide it at all. Even though these two (information hiding and encapsulation) are different, they are usually used together by making the attributes of your class private data members and providing getter (accessor) and setter (mutator) methods to them. Having said that, let us look at an example:

public class InformationHiding {
   private Position position;

   public InformationHiding(double latitude, double longitude)
      throws IllegalArgumentException {
      //make sure you have proper values for latitude and longitude
      if (latitude >= -90 && latitude <=90 && longitude >= -180 && longitude <= 180) {
         throw new IllegalArgumentException();
      }
      position = new Position(latitude, longitude);
   }

   public Position getPosition() {
      return position;
   }
}

Can you spot the problem with this code (beside the lack of synchronization)? Let's see how we can break the check for proper values of latitude and longitude:

InformationHiding inf = new InformationHiding(45, 120);
Position pos = inf.getPosition();
pos.latitude = -100; //illegal value
pos.longitude = 240; //illegal value

How can that be? We did make the position data member private? The problem is that we returned a reference to that member. This is a common mistake. Even when you generate the getter method from inside our IDE (i.e. Eclipse), it returns a reference to the attribute, rather than a copy to it. How can we fix this? Easy, just return a copy of the data member:

public Position getPosition() {
   return new Position(position.latitude, position.longitude);
}

That's it! You could have used the clone method to make a copy of the object, but then some changes need to be made, like not implementing clone by using the constructor.

There are some cases when we do not need to return a copy of the data, namely when we deal with immutable objects (like Strings and the wrapper classes).

Tuesday, February 10, 2009

Android Presentation

Today I did a presentation to a group of students on Android, basically an overview of the platform. If you are interested, you can find the presentation here. Any comments are welcomed!

Thursday, January 22, 2009

BOLT - the Java-based Browser

What intrigued me about BOLT (which is in a beta version at the moment of this writing) is the fact that it is written in Java (Java ME). It is designed for entry-level phones (with MIDP 2.0 and CLDC 1.0 or higher), but certainly it runs just fine on smartphones too. It is considered to offer fast and secure web browsing. How secure? 128-bit SSL Connections, filtering done on the server to protect you from malicious code, certification error notifications, and pop-up blocker. How fast is it? Reports have mentioned that on a Nokia 6120 (which runs on the S60 platforms), BOLT loaded the phonearena.com website in 14 seconds, while the built-in browser loaded it in 40 seconds.

BOLT provides ECMA Script 262 JavaScript support (asynchronous java script will work) , but does not currently offer support for Java Applets. Data reductions and lower power consumptions are also achieved.

If you are looking for screenshots (and further test results), head to phonearena.

Friday, September 19, 2008

JNI Example

JNI stands for Java Native Interface, which allows you to use, inside your Java application, code written in other programming languages. I will walk you through an example (developed under Windows) of using JNI.

Here are the main steps we need to follow:
- Create a java application that declares the native method.
- Compile the program.
- Generate the header file using javah.
- Implement the native code inside a C application.
- Compile the C code and generate the native library (dll).
- Run the java program.

Let us go through each of these steps:

1. Create a java application that declares the native method.

/**
* Shows a simple example of using JNI
*/
public class JNIExample {
//Declare native method
private native void displayMessage();

public static void main(String[] args) {
//Load native library
System.loadLibrary("JNIExample");
//Call the native method
new JNIExample().displayMessage();
}
}


2. Compile the program.
javac JNIExample.java

3. Generate the header file using javah.
javah -jni JNIExample

4. Implement the native code inside a C application.

#include
#include
#include "JNIExample.h"

JNIEXPORT void JNICALL Java_JNIExample_displayMessage
(JNIEnv *lEnv, jobject lObj) {
printf("This is a JNI Example!\n");
return;
}

The method signature matches exactly the one from the JNIExample.h header file.

5. Compile the C code and generate the native library (dll).
Open a Visual Studio (or similar) command prompt. In my case, it was located under "start->Programs->Visual C++ 2005 Express Edition->Visual Studio Tools->Visual Studio 2005 Command Prompt".
Run the command from the directory where you have the JNIExample.c file:
"cl -I"c:\Program Files\Java\jdk1.5.0_08\include" -I"c:\Program Files\Java\jdk1.5.0_08\include\win32" -MD -LD JNIExample.c -FeJNIExample.dll". Your path to the include directory might be different, so make sure you adjust that according to your settings. The -LD option makes sure that the compiler generates a DLL file. The -MD option makes sure that the DLL generated is linked with the win32 multithreaded C library.

6. Run the Java program.
java JNIExample

Some problems I ran into it while testing the code:
- I was missing the msvcr80.dll file, so I downloaded from here and copied it to c:\windows\system32 directory.
- Even though a manifest file was created, I hade to embedd it inside the dll. I have used the following link to solve the problem: http://msdn.microsoft.com/en-us/library/ms235591(VS.80).aspx. Here is the command: "mt.exe -manifest JNIExample.dll.manifest -outputresource:JNIExample.dll;2"

Tuesday, August 26, 2008

Basic Set operations in Java

How do we work with Sets in Java when it comes to performing the basic operations: Union, Intersection, Subset, Complement, Cartesian Product (for which there is no standard Java method in the Set Interface)? Do we have some kind of a collection that maps this mathematical concept into Java? Yes we do.

The Set Interface models the mathematical concept of a set and it is a Collection that contains no duplicate objects. Before talking about the specific methods that we will use, you must be aware of the three most used Set implementations: HashSet (uses a hash table to store its elements), LinkedHashSet (HashSet that also maintains a doubly-linked list running through all of its entries), and TreeSet (a sorted set).

Assume we have two sets s1 and s2. Going back to the basic set operations, we have:
- Union: the union of sets s1 and s2 is a set whose elements are contained in either set s1 or s2.

Java: s1.addAll(s2) - adds all elements from s2
in s1 if they are not already present.

- Intersection: the intersection of two sets s1 and s2 is a set whose elements are in both s1 and s2.
 
Java: s1.retainAll(s2) - s1 becomes the intersection of
s1 and s2.

- Subset: s2 is a subset of s1 if all elements of s2 are also elements of s1.

Java: s1.containsAll(s2) - returns true if s1 contains
all of the elements of s2.

- Complement: the complement of s2 in s1, denoted s1 - s2, is a set of all elements that are members of s1 but not of s2.

Java: s1.removeAll(s2) - removes from s1 all the
elements that are also contained in s2.

- Cartesian Products: the Cartesian product of two sets s1 and s2 is the set of all ordered pairs (x, y), where x is an element in s1, and y is an element in s2.

Java: public static Set computeCartesianProduct(Set s1,
Set s2) {
Set
result = null;
if (s1 == null || s2 == null) {
throw new IllegalArgumentException();
}
if (s1.isEmpty()) {
return s2;
}
if (s2.isEmpty()) {
return s1;
}

result = new HashSet
();
for (Object obj1 : s1) {
for (Object obj2 : s2) {
result.add("(" + obj1 + "," + obj2 + ")");
}
}

return result;
}


UPDATE (04/30/09): For the Cartesian Product operation above, I have used a raw type for unknown set element type. As of Java 1.5, you should consider using generics. For example, you should use an unbounded wildcard type for the input parameters of the computeCartesianProduct method, making the above code type safe and more flexible. This implies that instead of using the declaration Set s1, you should actually have Set<?> s1.

Friday, August 22, 2008

Sun Certified Java Programmer (SCJP) Exam

Today, I passed the Sun Certified Java Programmer (SCJP 1.5) exam. Throughout this post, I will share my experience preparing for it.

Before I get started, a little bit of background. I started developing in Java in 2001 (second year of college). Most of the software I have written was using the standard and mobile editions of the Java Platform. I have some knowledge of the enterprise world of Java, but mostly through Servlets and JSPs than anything else. In addition, I took a 6-months Java tutorial back in 2005 that covered OO Topics and Java Core (everything up to concurrency), Java Advanced (concurrency, networking, RMI, JDBC, XML) and Java Enterprise (Servlets, JSP, Custom Tags, JMS, EJB). Hence, I was not knew to this technology when I first started preparing for the SCJP exam in mid June (I also became a SCJA in January this year).

First step was to find a study book. This was not hard since I already knew about the SCJP for Java 5 Study Guide from Sierra and Bates (I already had the 1.4 version of the book). This is an excellent material, no doubt about it. It has a complete coverage of the exam objectives, examples, exercises, exam watches, basically anything you would possibly want from a certification book. Highly recommend it. I only went through this book once, done most of the exercises, and took the free practice exam that comes with the CD (you also get a bonus MasterExam practice test). Once I indentified my weaknesses, I went over again through the specific chapters in the book. At the end, I took the MasterExam practice test and did a little better. How many times you read the book really depends on you, on how familiar you are with Java, on how fast you graps the topics detailed there. I read about people who read the books as many as five times. If you think it helps, and you have time, it is up to you!
Now I have to mention that the two practice tests were the hardest from all the test that I have done afterwards, harder than the exam, hence if you nail these tests, the real exam will feel much easier. It might be harder also because, like other practice tests I took, when you get a multiple-choice question, they don't specify how many correct answers you have, while the real exam, and some of the other test, does. I understood the reason why it is not specified, but I would have wanted an option from where to choose if I should be given, or not, the number of correct answers.

Next step, a combination of taking many mock exams, and reading online SCJP notes. The best place to go for this is to the Java Ranch SCJP Forum webpage. How much it helped me? Enormous! Beside the benefit of having a forum specifically dedicated for SCJP, you get links to basically anything that you might want (and need) for this exam, such as faq, notes, mock exams, etc. Such a pool of resources gathered under one roof is almost impossible to find. Two thumbs up for everybody involved there!

If you want commercial practice tests, I would suggest Whizlabs, uCertify, Sun's own ePractice Certification Exam. From what I read, and from my own experience, I would say that Whizlabs is harder than any practice exams I know (except the one from the book). It contains tips, study notes, and 4 practice exams - best overall preparation kit. uCertify is a bit easier than the real exam, and it contained minor software errors, but was a good resource in the end. Bundled in it come 7 tests, tips, notes, etc . Sun's web-based practice exam came the closest to how the real exam was (which kind of makes sense, I know). This is the main reason I bough it. The score that I got form the third (and last) practice test was the one I got in the real exam.

Going through many mock exams and practice tests, I started writing my own SCJP Notes document. It contains everything that I thought was essential for the exam (inspired from the book and many existing online notes), together with things I have missed at tests (my own weaknesses if you like). You can read the document here.

As for the exam itself, you get 210 minutes (I was done in around 130 minutes). Honestly, I thought I would do worse than I did. I was unsure on some of the answers I had given, but when you take so many mock and practice exams, when you read from the many resources available out there, you have to start trusting your guts. And this is mostly true on API related questions, i.e. does the reverse method exist in both String and StringBuffer classes? What about replace? Java 1.5 specific questions (topics not present on older versions of Java) were on the exam quite often (such as generics, autoboxing, varags, etc). The Thread-related questions were harder than I expected, and I did the worse on that section than I did on any other (only 75%). In the practice exams, threads were one of my strongest suites. If you aks me, Concurrency, Generics and Collections are the hardest topics around.

What can I say more? Good luck to any of you who want to take this exam, and if you have any questions, drop me a comment.

Monday, July 28, 2008

Oracle Application Diagnostics for Java

Oracle Application Diagnostics for Java is a solution for diagnosing applications in production environments and was implemented by enhancing the native diagnostic capabilities of the Java Virtual Machine (JVM). Here are some of the key features taken from here:

  • Low overhead - there is no impact on the application on which the monitoring is done. Examples of application resource consumption include requests waiting on database, I/O, network, etc.
  • Real-time transaction tracing - used to view the application activity (such as threads and their execution stack, waiting time due to locks, etc).
  • Cross-tier correlation with Database - thus showing the state in which the database is (i.e. locks, tables, SQL statements that cause problems).
  • Memory leak detection and analysis - abnormalities in memory consumption are detected; heap dumps can be taken without impacting the application running.
  • Multiple platforms supported - runs on all major application servers.

Tuesday, July 1, 2008

Java Developer’s Journal June 2008 Issue

Two articles of the June Edition of JDJ I enjoyed. The first one talks about (Enterprise) Comet, an event-driven application architecture where the server pushes data asynchronously to a client, without the need of pulling, and by means of a always-on HTTP connection between the client and the server. Therefor, the client does not need to explicitly request any data from the server; any application that requires real-time updates could benefit. Such examples are mentioned in the article: "chat applications to exchange messages on social networks; online games; stock prices from online trading platforms; tools for online collaboration; betting odds for gambling sites; news feeds; and results from sporting events."
The article describes how Comet works, which are the supported technologies, the benefits and drawbacks of this architecture, and many more. If you are looking for articles on Comet, they can be found on the Comet Daily website.

The second article describes how Java can be used in real-time systems. Here you can read about Sun's Java Real-Time System (Java RTS), which implements the Real-Time Specification for Java (RTSJ) and its Real-Time Garbage Collector (RTGC). The article describes key concepts from the real-time realm, such as jitter, determinism, predictability, throughput. Furthermore, the main sources of jitter are explained, for instance class loading, synchronization, compilation, and garbage collection, together with how the Java RTS alleviates each of them.

Other articles could also trigger your interest, so go ahead and give the JDJ a try.

Monday, June 23, 2008

Wrapper Objects, Autoboxing, ==

Let us look at the following Java code:

Integer lInt1 = 5000;
Integer lInt2 = 5000;
if (lInt1 != lInt2) {
System.out.println("Different Objects");
}

Integer lInt3 = 100;
Integer lInt4 = 100;
if (lInt3 == lInt4) {
System.out.println("Same Object");
}

When compiled and run, the output will be:

Different Objects
Same Object

Apparently, in order to save memory, when using autoboxing to create two instances of the Integer (and Short) wrapper objects, they will be always == if the primitive values that they hold are from -128 to 127. Why on earth would the Java gods only allow this to happen for values from that interval, and not make it for any (legal) value possible?

Wednesday, May 28, 2008

How does Google manage Android's code

In a recent article, I read that Google currently uses Perforce as its source code management tool for Android. The reason why they chose this particular tool can be found in a comparison of other SCM systems (also Wikipedia offers more information if needed). In addition, it is worth mentioning that Android consists of around 8 million lines of Linux code, and about 11 million lines of Java/C++ and maybe some Python code. Since they want to open source around 8.6 million lines of code, Google will move away from Perforce when it comes to managing Android code, and use Git instead, an "open source version control system designed to handle very large projects with speed and efficiency".

As a side note, one particular difference between Git and other SCMs is how Git handles data corruption. Most of SCMs have no checksums, and if they have, it's not really strong (CRC usually). Git goes further, and, beside using CRC and Adler32, it also utilizes cryptographic hashes. If you are interested in a book on Git, you have to wait a bit more.