The ‘final’ Frontier in Java

No Comments

Although this post came about primarily to help my son learn Java, it still amazes me how many professional developers do not understand this basic premise in Java (Programming Language) even after working with it for Years. I am yet to find any Java book that opens with Big Chapter on this very critical topic, instead they mention it in a few hardly intelligible sentences. Meanwhile Java continues to gain momentum as most popular language, primarily because of how easy it seems to use! Let me be the first to tell you that Yes, it is Easy, provided you fully grasp the concepts outlined below.

Quick primer before diving into Java – most operating systems organize memory for a running program as Heap and Stack. These are just designations for areas of memory allocated to your program, but the way they are utilized differs slightly as we’ll see below. And if you don’t know what Object is, for our purposes it’s just a little set of data organized together.

There is fundamental difference in Java between Object variables and Primitive variables. The latter is those built-in types we all grew to love from most languages, like int, long and float. They are actually very high performance as well because they are quickly allocated on the Stack and CPU operates on them via Native commands.

Meanwhile Objects in Java are just Pointers! Let me demonstrate with this simple example:

   1:     public static void main(String[] args) {
   2:        
   3:        int a = 1;
   4:        int b = a;
   5:        a=3;
   6:        
   7:        System.out.println("A: "+a+" B: "+b);
   8:        
   9:        ArrayList aLst = new ArrayList();
  10:        ArrayList bLst = aLst;      
  11:        aLst.add("I Live in List");
  12:        
  13:        System.out.println(" A List Size: "+aLst.size()+
  14:                           " B List Size: "+bLst.size());
  15:     }

Although lines 3-5 look conceptually similar to lines 9-12, the output is very different:

A: 3 B: 1
A List Size: 1 B List Size: 1

With Primitives we see that assigning a into b truly made a copy, so that when we put 3 into a later, nothing happened to b. Two_Java_Pointers_at_ArrayList_ObjectMeanwhile, assigning aLst into bLst seems to act differently, as modifying aLst makes something magically appear in bLst!

Although our most respected Java Designer Mr. Gosling tried to hide the pointers complexity away from average developer, it still shows through sometimes, especially when calling Methods and passing Objects around:

   1:     public static void callMeMaybe(ArrayList third, int howOften) {
   2:        howOften = 1;
   3:        third.clear();
   4:        third.add("+1 800-555-1212");
   5:     }
   6:   
   7:     public static void main(String[] args) {
   8:   
   9:        int a = 800;
  10:        ArrayList first = new ArrayList();
  11:        ArrayList second = first;
  12:        first.add("Unlisted Number");
  13:   
  14:        callMeMaybe(second, a);
  15:   
  16:        System.out.println("Our List: "+first);
  17:        System.out.println("A: " + a);
  18:     }

And here is the output, hopefully what you expected by now:

Our List: [+1 800-555-1212]
A: 800


What has happened to our Unlisted Number? And if the evil callMeMaybe method was able to eliminate it, why did we not extract the essential howOften to call information from that same method?Three_Java_Pointers_at_an_Object.jpg

The basic way to understand the difference is to simply remember the Primitives versus Objects distinction. The more complete explanation is that Objects live in the Heap, while pointers to objects (such as first, second and third in our example) live along with Primitives, in the Stack. Each time our program enters a method, new variables (sometimes with copies of values from existing variables) get created on the Stack, and once method is finished, they are released. But even though once callMeMaybe method finishes our third variable gone into the great beyond (along with howOften variable), the object it was pointing to lives on in the Heap, and still available for first to see.

Having understood this we are finally ready to discuss Java’s ‘final’ keyword Winking smile

Simply put, when this keyword is placed on variable definition, you can only give this variable one value in it’s lifetime. A more complete explanation about the use of final keyword can be found on Wikipedia. My personal recommendation is that you avoid using this keyword, except when defining some truly Constant value in all upper case, like so:

public static final int REQUIRED_HOURS_OF_SLEEP_FOR_HEALTHY_HUMAN = 8;


And especially avoid using it when declaring Object referencing variables, since it does Not do what you would expect. As a simple example, if we were to define third variable in example above as final, it would have no impact on our program behavior or output!

While there are few other cases where final should be used, remember that Optimization is Not one of them.

Good Luck!

Got Flash Blues? Dalvik VM to the Rescue!

Comments Off

Adobe Flash Platform got some bad press lately, and its exclusion from iPad is a major slap in the face to Adobe by Steve Jobs himself. Even though millions of sites out there (including this one) use Flash to liven up things and provide extra interactivity, Apple is willing to leave users to stare at Big Empty Boxes on iPad, rather than add Flash support.

Android Logo To be fair, I myself did a lot of Flash/Flex development and still do! I really like what ActionScript can achieve, much more so than messing with JavaScript and CSS/HTML. But, times are tough, so here is my proposal:

How about we setup an Open Source project to build Flash alternative based on Dalvik VM and some existing Android platform components. We already know that it’s very capable, and if Google is true to its mantra, they wouldn’t mind sharing! Why not reuse the great UI library and 3D API’s, and others, and bring them into the browsers on all platforms – Windows, Unix and of course, Mac and iPad/iPhone! Can’t we all just get along?! Plus with JIT for Dalvik, and potential for native hardware video acceleration on Windows/Mac/Ubuntu/Handsets, I see very bright future!

I am not ignoring Silverlight or HTML 5, I just don’t see either as viable solution. Silverlight is still proprietary and you need specific Microsoft tools to develop for it, while HTML 5 feels like a bit “future-ware” and even when materializes, it’s unclear that it can provide all the richness of visual effects, 3D support, overall speed and pixel level manipulation which we expect in this day and age.

But what about JavaFX you ask? Feels like DOA to me, sadly. I love Java, which is yet another reason why I think Android approach is great, but JavaFX is just “overweight” out the door, and many posted about other major shortcomings.

Plus true modularity is still not there with neither technology! Why are we (developers) still forcing users to go through complex installation ritual to get new software on a system? Why does it have to be a gamble, especially when installing complex applications, whether it will interfere with other applications on the system and break things?!

So, I want to see comments! I know it’s rather big project, so without some people weighing in as to it’s merit (or with offers of participation), I am not going to bother starting even. Besides, probably Googlers are already doing it, whether in their 20% or even as main task, who knows…

UPDATE: I just discovered that someone implemented Flash player in JavaScript!? I didn’t think it was possible, but it is seemingly done using HTML5 browser features in modern browsers. More details and browsers compatibility list on the Gordon project on Github.

Google App Engine and Language Wars

2 Comments

appengine.gif Yesterday I attended Google Application Engine Hackathon in Atlanta. I guess it’s the kind of thing that one could call Geeky Weekend Fun, programming all day, with like-minded folks, trying to create something.

My application was a bit too ambitions, so it didn’t get finished, but I will get back to it in the coming days. Best app that did get finished, and someone in that group even snagged a domain name for it, was LangWar.com . The source code is here, and yes, it’s all in glorious (gore-ous?) Python.

My thoughts? I still love App Engine as a concept, but it still remains Love/Hate relationship because of Python. With all due respect to the language, it doesn’t feel like it is best suited for web development, even when using popular Django template framework. I am sure it will become Love/Love, if Java becomes supported by GAE! So, Googlers, grab OpenJDK and get right on it!

The whole Hackaton experience prompted my thinking again about the characteristics of “good” or “best” programming language. As always, the big thing about defining “best”, is identifying characteristics to rate on. So, I am going to try and put short list together:

  • Ease of Expression – How easy is it to put into “words” what is it you want computer to do for you
  • Speed – How fast can computer accomplish what you wanted from it
  • Integration – This one is an attempt for catch all category, from how well it works with other existing tools, to cross-platform / cross-OS compatibility, to Visual Editor integration

I am really trying to keep list to top 3, but many people will argue that best programming language is simply the one that you know. That’s fine when you developing something by yourself, in a Tundra, with no hope of survival or escape. In real world, however, software gets developed by many people, and usually goes through many cycles of corrections and improvements. You need other people to be able to locate piece of code that does “X”, and be able to easily read and modify it.

Turning into long post, so I will stop. The idea is mostly to provoke some thought. Some people will argue that in today’s world, the Speed factor is irrelevant, since computers are getting faster and faster. Others argue that “Ease of Expression” is overerrated and entirely relative. For them, code that says ‘ a = !regex(‘[dfqwer]x643DA*-’,*&x) ’ is easy to write and quick way to express what they mean… hmmm…

Recursive Algorithms and other sins

2 Comments

java_recursion My sister is just starting studies for Computer Sciences, and unlike what I remember from my days, in the first Intro course, they are trying to fill her head with nasty recursive algorithms.

What gives? First, I want to hear from the community, who else thinks that studying recursive algorithms is a good introduction to Computer Science, for someone who doesn’t know what is a Parser, Whitespace or Compiler. They used Java as a language for intro course, which I think actually was a good idea, but venturing into recursion, why?!

Seriously, how often in your daily developer career and activities would you use it? Even if it is needed, who among us wants to risk blowing up the stack, when so many other more optimal solutions are usually available?

In general, I think Computer Sciences have lost their way lately. The Science of it, at least. It really needs to refocus on solving real problems. What are real problems, you ask? How about starting off with creating next generation of web-like networking platform? Or new wave of development tools and languages? Object Oriented was invented too many years ago, and the Intentional Programming hasn’t really taken off, nor have other ideas. Surely there are better ways! Who’s trying? There are some novel ideas in XML use as development platform in many areas, especially XAML in Vista‘s WPF layer.

Lets see what they study next, if in the intro course they mastered Recursion, I have high expectations now! Meanwhile, post in comments what you think the next great frontier in CS research should be, lets get some collective wisdom going here!