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.

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