ActionScript for Java developers, Part 1

Learn how ActionScript 3 differs, and doesn't, from Java

Hybridizing Java sounds sexy but learning ActionScript ... not so much. In this two-part article, Chet Haase gets you started toward the Great Migration, with a Java developer's perspective on what's different about ActionScript 3 and its flashy, scripty syntax. In Part 1: An overview of ActionScript 3 and how its basic syntax and class behavior differs from Java's. In Part 2: An advanced look at how ActionScript handles properties, dynamic behavior, and functions. Level: Intermediate

About a year ago, I packed up my things and moved dimensions. I went from programming full-time in Java to working on the Flex team at Adobe, where I now program in ActionScript 3. I was looking forward to the change because I think that an occasional radical shakeup usually works out well, unless you're talking about babies or champagne bottles.

But I wasn't quite so sure about the language barrier.

I'm not an expert in programming languages -- at all. I'm just a graphics geek who learns enough about languages to get the job done. And I figure we can all do what we need to in any language as long as we understand the rules and constraints. But I did come to the new platform with a just a tad of supercilious Java bias, thinking "Isn't ActionScript that toy language that designers use for sprinkling code into animations in the Flash authoring tool?" I mean, any language with script in its name is obviously going to be a step down from the mighty Java. (Or, as Neil Young put it in his surreal cameo appearance at JavaOne 2008, "The Jay-va.") Right?

I was therefore pleasantly surprised to find that ActionScript 3 is actually quite a powerful language, and was syntactically similar to Java in many ways (see Figure 1). Yes, it's a scripting language with dynamic behavior and less type strictness than we have come to expect from Java. But it also has a lot of similar type behavior, object-oriented structure, and package/class/method/field organization that makes it look, well, almost Java-like.

A similar class written in Java and ActionScript 3.
Figure 1. A similar class written in Java and ActionScript 3. Differences are shown in bold. (Click to enlarge.)

So while I'm not a language expert (I'll keep emphasizing that, to make sure that nobody sends me questions about lambda expressions or BNF grammars or anything else I can't answer), I thought that it would be useful to take a step back from both languages and compare them from this programmer's point of view. I'll compare various aspects of the languages to see what ActionScript 3 looks like to a Java developer. In so doing, I hope to help you avoid some of the pitfalls and misconceptions I encountered in my own migration to the Flex SDK.

On the delicate art of comparison

The goal of this article is not to depict one language as better than the other. I think that all languages have their place (I could throw in an unkind jibe here about some older or untrendy languages, but I will pretend that I am above that). Instead, I just want to examine things that are similar and different about Java and ActionScript 3, and what these characteristics contribute to how we use each language.

ActionScript and Java in Antwerp

The ideas for this article came straight out of a presentation that James Ward and I gave at the Devoxx conference in Antwerp in December of 2008. James and I played hooky one morning and wrote many of the code examples here over a couple of strong cups of coffee in the hotel lobby. A recording of that presentation should be posted online eventually at the excellent parleys.com Website. (You'll have to go to Antwerp yourself for the hotel coffee, though.)

To compare the two languages, I'll break down their differences into broad categories and look at several examples per category. To keep things manageable, this article is broken into two parts. In this first part I will introduce the topic, start the conversation, and build the kind of tension and suspense that you would expect from any decent multi-part programming discussion.

More to the point, I'll cover the following topics:

  • Introduction to ActionScript: Get some context on the platform for which ActionScript is intended: Flash, Flex, and all that.
  • Syntax: Many of the differences between Java and ActionScript 3 are like those highlighted in Figure 1: purely syntactic. The differences are important because you'll certainly hit on them if you try writing an application in Flex, but they needn't really change the way that you think about the language or the way that you solve problems. They are just new tricks for old fingers.
  • Classes: Java and ActionScript 3 employ a similar class structure, but once again the differences are worth discussing. I'll focus on class behavior, which is where the two languages most diverge.

So Part 1 will focus on the basic stuff that any Java developer might be curious about when exploring (or considering) software development for the Flash platform, such as Flex application programming. In Part 2 we'll get into some of the more complex topics and differences between the languages, like properties, dynamic behavior, and functions.

Lights, camera ... ActionScript!

ActionScript is the language that is used for programming Flash applications. When users of the Flash authoring tool write code snippets for their program logic, they do so in ActionScript. When developers write programs intended to run on the Flash platform, they do so in ActionScript. And when Flex developers write code using the Flex libraries that produce applications that deploy and run on the Flash platform, they do with ActionScript.

But ActionScript has changed over the years. In particular, ActionScript 3 came out in 2006 with FlashPlayer 9 and Flex 2 and represented a significant change in the core language. All of the old capabilities and syntax were still there, but more powerful mechanisms familiar to Java developers were introduced, including classes and packages, types, and a new runtime-compiling VM to handle it all.(Actually, type annotations, classes, and interfaces were available in ActionScript 2, but only as syntactic sugar to be removed at compile time to accommodate the older ActionScript 1 interpreter. ActionScript 3 Integrates these features for real.)

Meanwhile, Flex came along a few years ago, and is now at version 3. Flex is a set of libraries that add important functionality like standardized GUI widgets to the Flash platform to make programming powerful Flash applications easier. Flex also adds an XML-based language called MXML that is pre-processed into ActionScript during compilation. Developers use MXML for the declarative parts of their application, such as what the GUI screens look like, and program in ActionScript directly for their core application logic. I won't cover MXML here because it is not really a part of the ActionScript language itself. I mention it because it comes up in some of the examples and language features that I will discuss later on.

I will focus on the modern features of ActionScript, sticking to what ActionScript 3 provides. Many of these features may date back to earlier versions, but to keep things simple I will just assume that we are talking about the latest version, since that is the version that most Flash and Flex developers have access to today.

I'll also start using the abbreviation "AS3" to mean ActionScript 3 now, because typing out "ActionScript 3" every time is getting tedious. When I invent a language, I'll start with as short a name as possible. Kernighan & Ritchie did it right.

The wages of syntax

I've always thought that one of the most enjoyable activities in life was comparing syntax rules of different languages. Okay, perhaps not. But it is a good place to start when comparing the languages overall, so we'll start with several simple examples of important syntactic differences between AS3 and Java.

Variable declaration

Java declares variables like this:

public int blah;
  public Object foo = new Object();

AS3 declares variables like so:

public var blah:int;
  public var foo:Object = new Object();

Variable declaration is where I have tended to bruise my fingers in the Java-to-AS3 migration. After declaring thousands of variables in Java over the years, my fingers know just what (not) to do. And after months of typing hundreds or thousands of declarations in AS3, I still find myself having to go back and add the var keyword, or switch the type definition to live after the variable. It takes some getting used to coming from Java type-typing.

Undefined != null

Java has no concept of "undefined":

Object foo;
  Number num;
  System.out.println(foo);
  // outputs 'null'
  System.out.println(num);
  // outputs 'null'

AS3 has "undefined", "null", and "NaN" concepts:

var foo;
  var bar:Object;
  var num:Number;
  trace(foo);
  // outputs 'undefined'
  trace(bar);
  // outputs 'null'
  trace(num);
  // outputs 'NaN'

Note the use of trace() in my AS3 snippets. It's a library difference, not a language difference, so I won't discuss it here. Hopefully it is clear that trace() is the equivalent of System.out.println(). But since outputting to the command-line still ranks as one of the developer's main weapons against bug infestation (right above asking the person in the next cube) I thought I'd at least give a shout out to the lowly trace() statement.

Package declaration

Java declares packages in Java source files:

package foo;
  class FooThing {
  }

AS3 places classes inside package blocks:

  
 package foo {
    class FooThing {
    }
  }

These amount to the same thing: they are both ways to organize and control the visibility of global names. One difference is that the Java package declaration is scoped to the whole file so all classes in that file are put into that package, whereas AS3 allows multiple package definitions per file.

Scope

Scope in Java is clearly defined as being within the current block:

 
 // using i for both is fine – completely separate scopes
  public void foo() {
    for (int i = 0; i  < 10; ++i) {}
    for (int i = 0; i  < 5; ++i) {}
  }

AS3 variable scope is at the level of the function itself -- regardless of whether the variable is defined within an inner block:

// causes a compiler warning
  public function foo():void {
    for (var i:int =  0; i < 10; ++i) {}
    for (var i:int =  0; i < 5; ++i) {}
  }
  // better:
  public function foo():void {
    var i:int;
    for (i = 0; i  < 10; ++i) {}
    for (i = 0; i  < 5; ++i) {}
  }

Metadata

Java has annotations:

@Foo
  public class Bar {
    @Monkey
    String banana;
  }

AS3 has metadata:

[Foo]
  public class Bar {
    [Monkey]
    var banana:String;
  }

Metadata is used for declaring such things as hints to MXML, like the default property to assume when instantiating the class in MXML, and hints for tools, such as default values for properties.

Semicolons

Java;

requires;

semicolons;

after;

statements;

AS3

does

not

except; to; separate; multiple; statements; on; a; single; line;

But please, on behalf of the readers of your code: use semicolons anyway. After so many years of coding in other languages with line-ending syntax, it just makes code more readable, don't you think?

Final vs. const

Java uses the final keyword for constant values:

public static final int FOO = 5;

AS3 uses the const keyword:

public static const FOO:int = 5;

Casting call

Java performs casts by putting the type in parentheses before the object in question:

float f = 5;
  int g = (int)f;

These parenthetical statements always look to me like the code is speaking to me quietly and discretely: "(Hey, psst! You should now consider this float to be an int. Pass it on.)"

AS3 casts look more like a function call through the type being cast to:

var f:float = 5;
  var g:int = int(f);

There is also another way of casting in AS3, using the as operator:

var g:int = f as int;

Exceptional coding

Java typically declares exceptions that are thrown:

public void foo() throws MyException
  {
    try {
      // really awesome code
    } catch (Exception e) {
      throw new MyException("AAAUUUGGGHHHH!");
   }
  }

AS3 throws exceptions without declaration:

public function foo():void
  {
    try {
      // really awesome code
    } catch (var e:Error) {
      throw new Error("AAAUUUGGGHHHH!");
   }
  }

Generically speaking

Java has generics and typed collections:

List<FooType> list = new ArrayList<FooType>();
  list.add(new FooType());
  FooType foo = list.get(0);

AS3 ... does not.

But AS3 does have typed arrays through the Vector class:

var vec:Vector.<FooType> = new Vector.<FooType>();
  vec[0] = new FooType();
  var foo:FooType = vec[0];

Some may wonder at the odd angle-bracket syntax of the Vector declaration. I'm not sure of the history, but I have a feeling that AS3 was just trying to achieve readability and angle-bracket parity with Java's generics.

XML

Speaking of angle brackets in code, Java handles XML processing through various libraries (many of them), such as JAXP, JAXB, SAX, Xerces, JDOM, etc.

AS3 has E4X integrated into the language itself for queries, manipulation, and the like.

var myXML:XML = <Grob>gable</Grob>;
  trace(myXML.Grob);
  // outputs 'gable'

The next level: Class behavior

As you've seen by now, AS3 classes look pretty much like Java classes. You haven't seen them yet, but AS3 interfaces also look eerily similar to their Java counterparts. But looks aren't everything (except with supermodels and wax fruit) and there are a few important distinctions in behavior that are worth investigating.

Constructors and permissive behavior

Java allows the same access permission specifiers (public, protected, private, and package-private) on constructors that are allowed on classes, fields, and methods:

 
 public class FooObject {
    private FooObject() {}
  }
  FooObject foo = new FooObject();
  // Compiler error

In AS3, constructors are always public:

public class FooObject {
    private function FooObject() {}
  }
  // Compiler error

Making a constructor private (in a language that supports it, like Java) is not a typical pattern, although it is helpful in some situations, like creating singletons. If you really want only one of something, then it's a good idea to prevent anyone but the class itself from creating it. A workaround used in AS3 involves throwing exceptions from the constructor when called from outside of your singleton accessor, but it is not quite the same thing.

Interfaces and properties

Java allows properties to be declared on interfaces:

public interface IFoo {
    public int blah = 5;
    public final int VAL = 7;
  }

*Both of these properties are implicitly static and final, even though they lack those keywords. Try it, you'll see.

AS3 does not allow properties on interfaces. Only functions can be declared on interfaces. Note, however, that you can declare properties with set/get functions; just not properties as fields. For example, this works:

public interface IProperties
  {
      function set blah(value:Number):void;    
      function get blah():Number;    
  }

If the get/set example here makes no sense, don't worry. You'll learn more about properties and these functions in the second half of this article.

Abstract, what's that?

Java allows abstract classes:

public abstract class FooObject {
    public abstract void foo();
  }

AS 3 ... does not. There is no concept of "abstract" in AS3.

Until next time ...

That's probably enough comparison to get a busy mind spinning, so I'll stop for now. I hope the examples here have whet your appetite, because there's more to come. In the second half of this article we'll get into the advanced topics of properties, dynamic behavior, and functions, with a similar line-up of code-based comparison and usage commentary from, well, me.

Acknowledgements

Thanks toJames Ward of Adobe for helping with the original presentation that these articles are based upon. Thanks also to Jeff Dyer, an actual language expert at Adobe, for providing a timely technical review and ensuring that I wasn't simply rattling off a bunch of half-baked opinions and outright stinking lies.

Chet Haase is a senior computer scientist on the Flex SDK team at Adobe Systems, where he spends most of his time working on animation and graphics-related technologies. He is the co-author of the Java book Filthy Rich Clients about graphics effects programming and the author of the humor book When I am King..., which has nothing whatsoever to do with Java, graphics, ActionScript, programming, or anything else.

Learn more about this topic

  • "Java EE and Flex: A compelling combination" (Dustin Marx, JavaWorld, January and February 2009) introduces techniques for integrating Flex clients with a Java back end.
  • "Client-side Java's evolutionary leap" (Jeff Friesen, JavaWorld, January 2009) looks back on 2008 as a momentous year for Java desktop and RIA technologies, with commentary from many leaders and innovators in client-side development.
  • "The ABCs of RIA" (Paul Krill, Infoworld, August 2007) is a survey of tools and frameworks used in rich Internet application development.
  • ActionScript Developer Center is the Adobe developer site for the language.
  • The Flex SDK Open Source site is the open source repository for the Flex libraries. You can download the latest release of Flex and build applications with it, or download the source code and build Flex from scratch. Also check out learning resources such as the Flex Developer Center site and Flex.org.
  • Flex Builder is Adobe's IDE for building Flex applications. The Flex SDK is free to use, but tools can make development easier.
  • The Flash Development Center provides resources for developers writing programs for the Flash platform, which can be done either with Flex, or by using the Flash APIs directly, or with the Flash authoring tool.
  • Filthy Rich Clients (Chet Haase and Romain Guy; Addison-Wesley/Sun Microsystems Press, August 2007) is a definitive guide to client-side development in Java.
  • Chet Haase regularly posts graphics, animation, and tutorial articles and videos to his technical blog Codedependent, and irregularly posts comedy writings to his non-technical blog Enough About You.

More from JavaWorld

Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more