Chapter 1. Why Java for Games Programming?

One of my assumptions is that the reader (that’s you) has had an introductory knowledge of Java, the sort of stuff gleaned from a semester’s course at college. Near the start of that course, you were probably regaled with Java’s many advantages: an object-oriented paradigm, cross-platform support, code reuse, ease of development, tool availability, reliability and stability, good documentation, support from Sun Microsystems, low development costs, the ability to use legacy code (e.g., C, C++), and increased programmer productivity.

Rather than explain each of these again, I will take a different approach and discuss Java’s suitability for games programming in terms of the typical misconceptions and complaints wheeled out by people who think that games must be implemented in C, C++, assembler, or whatever (just so long as it’s not Java).

Here’s the list of objections to Java:

  • Java is too slow for games programming.

  • Java has memory leaks.

  • Java is too high-level.

  • Java application installation is a nightmare.

  • Java isn’t supported on games consoles.

  • No one uses Java to write real games.

  • Sun Microsystems isn’t interested in supporting Java gaming.

It’s worth saying that I think almost all of these objections are substantially wrong. Java is roughly the same speed as C++. Memory leaks can be avoided with good programming and techniques like profiling. Yes, Java is high-level, but it offers more direct access to graphics hardware and external devices. Installation isn’t a nightmare if you use decent installation software. There’s a growing number of excellent, fun Java games, and an enormous amount of support available from Sun and Sun-sponsored sites.

Tip

If you’re keeping count, I haven’t disagreed with the lack of a games consoles port, which is a tad embarrassing for a “write once, run anywhere” language. Things may be changing in this category, as I’ll explain later.

A general point about these objections is that they had more validity in the late 1990s when the language and its libraries were less sophisticated and slower. Java’s user and developer communities are burgeoning and have produced a plethora of useful tools, online help, and code examples. The games forums dedicated to Java barely existed 2 to 3 years ago. Java is a great language for games programming, as I hope this book demonstrates. Now, back to the criticisms.

Java Is Too Slow for Games Programming

This is better rephrased as “Java is slow compared to C and C++, the dominant languages for games programming.” This argument was valid when Java first appeared (around 1996) but has become increasingly ridiculous with each new release. Some figures put JDK 1.0, that first version of the language, at 20 to 40 times slower than C++. However, J2SE 5.0, the current release, is typically only 1.1 times slower.

These numbers depend greatly on the coding style used. Java programmers must be good programmers to utilize Java efficiently, but that’s true of any language. Jack Shirazi’s Java Performance Tuning site (http://www.javaperformancetuning.com/) is a good source for performance tips, with links to tools and other resources. A recent benchmarking of Java vs. C++ by Keith Lea caused quite a stir (http://www.theserverside.com/news/thread.tss?thread_id=26634). He found that Java may sometimes be faster than C++. The response from the C++ crowd was typically vitriolic.

The speed-up in Java is mostly due to improvements in compiler design. The Hotspot technology introduced in J2SE 1.3 enables the runtime system to identify crucial areas of code that are utilized many times, and these are aggressively compiled. Hotspot technology is relatively new, and it’s quite likely that future versions of Java will yield further speed-ups. For example, J2SE 5.0 is reportedly 1.2 to 1.5 times faster than its predecessor (Version 1.4).

Tip

Hotspot technology has the unfortunate side effect that program execution is often slow at the beginning until the code has been analyzed and compiled.

Swing Is Slow

Swing often comes under attack for being slow. Swing GUI components are created and controlled from Java, with little OS support; this increases their portability and makes them more controllable from within a Java program. Speed is supposedly compromised because Java imposes an extra layer of processing above the OS. This is one reason why some games applications still utilize the original Abstract Windowing Toolkit (AWT) since it’s mostly simple wrapper methods around OS calls.

Even if Swing is slow (and I’m not convinced of that), most games don’t require complex GUIs; full-screen game play with mouse and keyboard controls is the norm. GUI elements maintained by Swing, such as menu bars, button, and text fields aren’t needed, and mouse and keyboard processing is dealt with by the AWT. The latest versions of Java offer an efficient full-screen mode by suspending the normal windowing environment.

My Program Is Slow Because of Java

A crucial point about speed is knowing what to blame when a program runs slowly. Typically, a large part of the graphics rendering of a game is handled by hardware or software outside of Java. For example, Java 3D passes its rendering tasks down to OpenGL or DirectX, which may emulate hardware capabilities such as bump mapping. Often the performance bottleneck in network games is the network and not the Java language.

Java Has Memory Leaks

When C/C++ programmers refer to memory leaks in Java, they probably don’t understand how Java works. Java doesn’t offer pointer arithmetic; typical C-style memory leaks, such as out-of-bounds array accesses, are caught by the Java compiler.

However, these programmers may mean that objects that are no longer needed by the program are not being garbage collected. This becomes an issue if the program keeps creating new objects and requiring more memory, and eventually crashes when the maximum memory allocation is exceeded.

This kind of problem is a consequence of bad programming style, since the garbage collector can only do its job when an object is completely dereferenced, meaning the program no longer refers to the object. A good profiling tool, such as JProfiler (http://www.ej-technologies.com/products/jprofiler/overview.html), can help identify code using excessive amounts of memory.

Tip

JProfiler is a commercial product; many open source profilers are listed at http://java-source.net/.

Another memory-related complaint is that the Java garbage collector is executing at poorly timed intervals, causing the application to halt for seconds as the collector sweeps and cleans. The Java Virtual Machine (JVM) comes with several different garbage collectors, which collect in various ways and can be selected and fine-tuned from the command line. Information on the performance of the chosen collector can be gathered and analyzed. A good hands-on explanation of this topic, centered around the JTune visualization tool, can be found at http://www-106.ibm.com/developerworks/java/library/j-perf06304/. Another possibility is GC Portal (http://java.sun.com/developer/technicalArticles/Programming/GCPortal/).

Java Is Too High-level

This complaint is the age-old one of abstraction versus speed and control. The details of the argument often include the following statements:

  1. Java’s use of classes, objects, and inheritance add too much overhead without enough coding benefit.

  2. Java’s machine independence means that low-level, fast operations, e.g., direct Video RAM I/O are impossible.

Statement 1 ignores the obvious benefits of reusing and extending Java’s large class library, which includes high-speed I/O, advanced 2D and 3D graphics, and many networking techniques, from lowly sockets to distributed agents. Also forgotten are the advantages of object-oriented design, typified by UML, which makes complex, large, real-world systems more manageable during development, implementation, and maintenance.

Statement 2 impacts gaming when we consider high-speed graphics, but it’s been addressed in recent versions of Java. J2SE 1.4 introduced a full-screen exclusive mode (FSEM), which suspends the normal windowing environment and allows an application to access the underlying graphics hardware more directly. It permits techniques, e.g., page flipping, and provides control over the screen’s resolution and image depth. The principal aim of FSEM is to speed up graphics-intensive applications, such as games.

Statement 2 comes into play for game peripherals, e.g., joysticks and game pads; machine independence seems to suggest that nonstandard I/O devices won’t be useable. Java games requiring these types of devices can utilize the Java Native Interface (JNI) to link to C or C++ and, therefore, to the hardware. There’s also JInput, a new game controller API.

An interesting historical observation is that the gaming community used to think that C and C++ were too high-level for fast, efficient games programming when compared to assembly language. Opinions started to change only after the obvious success of games written in C, such as Doom and Dungeon Master, in the mid-1980s. Also important was the appearance of cross-platform development tools that supported C, such as RenderWare.

Java Application Installation Is a Nightmare

The naysayers claim that the user needs to be a Java expert to install and execute a Java application, whereas most game players want to point and click on a few dialog boxes to get a game up and running. More specific comments include the following:

  1. Java (specifically, the JRE) has to be on the machine before the application will run.

  2. Code bloat since even small programs require a 15 MB JRE. Downloading this can be slow.

  3. Frequently changing JVMs make it hard to write code that will work for every possible version of Java.

  4. Nonstandard components are often required—e.g., Java 3D, causing even more installation problems.

  5. It’s impossible to compile the application for a specific platform.

  6. The .jar extension is commonly hijacked by other software (e.g., by compression programs) at execution time, meaning that the user can’t double-click on a JAR to get it to start.

  7. The JRE is slower to start up compared to a native compiled application.

All these problems, aside from perhaps 2 and 7, can be solved by using good installation software. I have two appendixes dedicated to installation: Appendix A is about install4j, a cross-platform tool for creating native installers for Java applications, and Appendix B is about Java Web Start (JWS), a web-enabled installer.

The code bloat comment is increasingly irrelevant, with many games weighing in at over 100 MB and many graphics and sound card drivers being made larger than 15 MB. Network speeds are a problem, especially overseas, but broadband usage is growing rapidly.

Sun Microsystems estimates that more than 50 percent of all new PCs come with a pre-installed JRE, though a game installer must still cater to the other 50 percent.

There’s some truth to point 7, but the slow startup time is fairly negligible compared to the total running time of an average game.

I was interested in what other Java games programmers had to say about this criticism, so posted it to the Java Games Forum as thread http://www.javagaming.org/cgi-bin/JGNetForums/YaBB.cgi?board=announcements;action=display;num=1092970902. The responses are similar to mine, though often phrased somewhat more stridently.

Java Isn’t Supported on Games Consoles

Unfortunately, this criticism has some justification. Video gaming is a multi-billion-dollar industry, with estimates placing revenues at $29 billion by 2007 with the market catering to over 235 million gamers. PCs and game consoles account for almost all the income, but only about 10-20 percent of it is from PCs, the majority coming from three consoles: Sony’s PlayStation 2 (PS2), Microsoft’s Xbox, and Nintendo’s GameCube. Sony is the dominant console maker, having nearly twice as many units in homes compared to Microsoft and Nintendo combined. Microsoft accounts for about 95 percent of the desktop PC market. Arguably, two important games platforms exist, the PS2 and Windows, and Java isn’t available on the PlayStation.

This problem has long been recognized by Sun. Back at the JavaOne conference in 2001, Sony and Sun announced their intention to port the JVM to the PS2. Nothing has been released, but there are persistent rumors about a JVM on the PlayStation 3, earmarked to appear in 2006.

In the future, Java may have a better chance of acceptance into the closed world of console makers because of two trends: consoles mutating into home media devices and the meteoric rise of online gaming. Both trends require consoles to offer complex networking and server support, strong areas for Java and Sun.

The Phantom console from Infinium Labs was announced at JavaOne in 2004 (http://www.phantom.net/index.php). It’s essentially a PC running an embedded Windows XP installation, with an nVidia graphics card, a hard drive, and a broadband connection. Most importantly for Java gaming, the Phantom will come with a complete JRE. It was demoed during Electronic Entertainment Exposition (E3) in 2004, where it was shown running Law and Order: Dead on the Money (which uses Java 3D).

Die-hard programmers may point out that it’s possible to get Java running on a PS2. One approach is to install Kaffe, an open source, non-Sun JVM, on top of PlayStation Linux. Kaffe can be obtained from http://www.kaffe.org/; details on Linux for the PlayStation are at http://playstation2-linux.com/. The gallant programmer will need a Java-to-bytecode translator, such as Jikes (http://www-124.ibm.com/developerworks/oss/jikes/).

The Linux kit adds a hard disk to the PS2, so this development strategy won’t work for ordinary PlayStations. Configuring the software looks to be far beyond the capabilities (or desires) of ordinary console owners, and I couldn’t find any documentation about using Jikes or Kaffe on a PS2. The PlayStation only comes with 32 MB of RAM, while a typical JVM and its libraries requires 5 to 10 MB, so how much would be left for a game once Linux was up and running?

The difficulties of this approach should be contrasted to the availability of feature-rich C/C++ tools and engines for consoles, such as RenderWare (http://www.renderware.com/) and Gamebryo (http://www.ndl.com/). They have a track record of best-selling games and can port games across the PS2, Xbox, GameCube, and PCs.

The lack of Java on consoles is a serious issue, but the remaining PC market is large. Microsoft estimates that there are 600 million Windows PCs, growing to more than 1 billion by 2010. Games on PCs benefit from superior hardware—such as video cards, RAM, and Internet connections—and can offer more exciting game play. There are many more PC games, particularly in the area of multiplayer online games. It’s estimated that 40 percent of all gamers will start playing online in 2005. Revenues may reach $1.1 billion by 2008.

Another rapidly expanding market is the one for mobile games, with sales of $530 million in 2003, potentially rising to $1.93 billion in 2006. There are perhaps 200 million Java-enabled phones at the moment.

No One Uses Java to Write Real Games

The word “real” here probably means commercial games. The number of commercial Java games is small compared to ones coded in C or C++, but the number is growing and many have garnered awards and become bestsellers:

Puzzle Pirates by Three Rings (http://www.puzzlepirates.com/)

This is a multiplayer pirate game that includes Tetris-like or Columns-like puzzles at various points. The client and server are written in Java. It won several awards during 2004, including the Technical Excellence and Audience Choice prizes at the Game Developers Conference.

Chrome by Techland (http://www.chromethegame.com/en/show.php)

Chrome is a futuristic multiplayer FPS (first person shooter) made up of 14 different missions, in an amazing variety of landscapes. It received a Duke’s Choice Award from Sun Microsystems in 2004 for the most innovative product using Java technology.

Law and Order II by Legacy Interactive. (http://www.lawandordergame.com/index2.htm)

This is a detective game written in Java, Java 3D, and QuickTime for Java. The first Law and Order sold over 100,000 units.

Kingdom of Wars by Abandoned Castle Studios (http://www.abandonedcastle.com/)

This is a fantasy game set in the world of Jairon.

Alien Flux by Puppy Games (http://www.puppygames.net/info.php?game=Alien_Flux)

Alien Flux is an exciting arcade shoot-em-up.

War! Age of Imperialism by Eagle Games (http://www.eaglegames.net/products/WAR_AOI/wai.shtml)

War! is a computer version of the award-winning board game from Eagle Games.

Runescape by Jagex (http://www.runescape.com)

Runescape is a massive 3D multiplayer fantasy adventure game. Clients can use a Java applet to play or download a Windows-based client application.

Star Wars Galaxies by LucasArts (http://www.lucasarts.com/products/galaxies/)

This one has its game logic coded in Java.

IL-2 Sturmovik by Ubi-Soft (http://www.il2sturmovik.com/)

Award winning WW II aerial combat using Java and C++, this and the new version (IL2-Forgotten Battles) are great examples of Java in games.

Pernica by Starfire Research (http://www.starfireresearch.com/pernica/pernica.html)

Pernica is an online fantasy role-playing game first implemented in Java 3D.

Cosm by Navtools, Inc. (http://www.cosm-game.com/)

Cosm is another fun online fantasy-based role-playing game.

C&C Attack Copter by Electronic Arts (http://www.eagames.com/free/home.jsp)

This is a free online action game based on the Command & Conquer series.

Roboforge by Liquid Edge Games (http://www.roboforge.com)

Train a 3D robot to fight in online tournaments. It was given an “Excellent 87%” by PC Gamer Magazine.

Galactic Village by Galactic Village Games (http://www.galactic-village.com)

Galactic Village is a massively multiplayer strategy game, written entirely in Java. Not yet finished though alpha versions have been appearing.

Wurm Online by Mojang Specifications (http://www.wurmonline.com/)

This is another massively multiplayer fantasy game, written in Java. It’s still in the alpha stages of development, but the screenshots look great.

Jellyvision (http://www.jellyvision.com/)

Jellyvision used a mix of Java and C++ in their popular Who Wants to Be a Millionaire (2000) and You Don’t Know Jack (1995) games. They employed Java for the game logic, an approach used in Majestic (2001) by Electronic Arts.

Vampire the Masquerade: Redemption (2000) by Nihilistic software (http://www.nihil-istic.com/).

Java was utilized as a scripting language in this highly acclaimed game.

Tom Clancy’s Politika (1997) by Red Storm Entertainment (http://www.redstorm.com/)

This game was written in almost pure Java. Shadow Watch (2000) and Tom Clancy’s ruthless.com (1998) mixed Java and C/C++.

A good source for nontechnical lists of Java games, both commercial and freeware/shareware, can be found on the Java games pages at java.com (http://www.java.com/en/games/). The pages divide games into several categories: action, adventure, strategy, puzzle, cards, sports, and so on.

Freeware/Shareware Games

Many Java games are out on the Web, but finding a game that’s written well requires a careful search. Many applets date from the late 1990s and were designed using the outdated JDK 1.0 and 1.1 with their feeble media APIs (e.g., graphics, sounds). The initial Java euphoria produced some less than exciting games, more concerned with technical trickery than quality. This large pool of useless applets got Java labeled as a toy language.

Recent versions of Java are different. The speed has improved and APIs crucial to gaming—such as graphics and audio—are of a high quality. There’s been a move away from applets towards the downloading of client-side applications using JWS.

Java’s backward compatibility allows the applets from 1996 to 1998 to be executed, and they’ll often run quicker than the original applets. However, it’s probably best to steer clear of these Java dinosaurs and look for more modern code.

Numerous web sites use Java games. The emphasis of the following list is on applications/applets for playing:

Java Games Factory (JGF) (http://grexengine.com/sections/externalgames/)

There aren’t many games at this site (about 50), but they’re all high quality. The aim is to show off various modern Java game technologies.

ArcadePod.com (http://www.arcadepod.com/java/)

Over 750 Java games, nicely categorized.

Java 4 Fun (http://www.java4fun.com/java.html)

Similar in style to ArcadePod, with a good set of links to other sites.

jars.com (http://www.jars.com)

A general Java site with a ratings scheme. There are many games, but a lot of them are old applets.

Java Shareware (http://www.javashareware.com/)

Another general site: look under the categories applications/games and applets/games.

Java Games Central (http://www.mnsi.net/tild rkerr/)

A personal web site that lists games with ratings and links. It was last updated in 2001.

Some of my favorite freeware/shareware games are:

Super Elvis; also known as Hallucinogenesis (http://www.puppygames.net/downloads/hallucinogenesis/hallucinogenesis.jnlp)

This game won the Sun Microsystems 2004 Technology Game Development Contest. Super Elvis can be downloaded from the puppygames web site using JWS.

FlyingGuns (http://www.flyingguns.com/)

A 3D multiplayer WWI fighter plane game/simulator. This came second in the contest but is my favorite.

Cosmic Trip (http://www.mycgiserver.com/tild movegaga/cosmictrip.html)

An arcade-style 3D game with striking graphics.

Squareheads (http://home.halden.net/tombr/squareheads/squareheads.html)

A multiplayer FPS (it came third in the developer contest).

Escape (http://javaisdoomed.sourceforge.net/)

A Doom-like FPS.

CazaPool3D (http://membres.lycos.fr/franckcalzada/Billard3D/Pool.html)

A pool game that allows online (single/multiplayer) play in an applet or as a standalone application.

Programmers looking for source code should start at one of the following sites:

SourceForge (http://sourceforge.net/search/)

SourceForge acts as a repository and management tool for software projects, many with source code. A recent search for (java + game) returned over 70 projects that had 40 percent or greater activity. One of the drawbacks of SourceForge is that deciding if a project is vaporware is difficult. Good projects that have been completed will show low activity after a time, dropping down the list of search results.

FreshMeat.com (http://freshmeat.net/)

FreshMeat maintains thousands of applications, most released under open source licenses. The search facilities are excellent and can be guided by game category terms. The results include rating, vitality, and popularity figures for each piece of software. A recent search for Java in the Games/Entertainment category returned nearly 70 hits. Many applications turn up at SourceForge and FreshMeat.

The “Your Games Here” Java Games Forum (http://www.javagaming.org/cgi-bin/JGNetForums/YaBB.cgi?board=Announcements)

Implementers can post links to their games, and (perhaps more importantly) users can post their opinions as follow-ups.

Code Beach (http://www.codebeach.com)

CodeBeach has a searchable subsection for Java games that contains nearly 90 examples.

Programmers Heaven (http://www.programmersheaven.com/zone13/)

It has a “Java zone” containing some games.

Sun Microsystems Isn’t Interested in Supporting Java Gaming

The games market isn’t a traditional one for Sun, and it’ll probably never have the depth of knowledge of a Sony or Nintendo. However, the last few years have demonstrated Sun’s increasing commitment to gaming.

J2SE has strengthened its games support through successive versions: Version 1.3 improved its graphics and audio capabilities, and Version 1.4 introduced full-screen mode and page flipping in hardware. Faster I/O, memory mapping, and support for nonblock sockets, which is especially useful in client/server multiplayer games, also appeared first in 1.4. Version 5.0 has a decent nanosecond timer at last. Java extension libraries, such as Java 3D, the Java Media Framework (JMF), the Java Communications API, Jini, and JAXP (Java’s peer-to-peer API) offer something to games programmers.

Sun started showing an interest in gaming back in 2001, with its announcement of the Java Game Profile, a collaboration with several other companies, including Sega and Sony, to develop a Java gaming API. The profile was perhaps too ambitious, and was abandoned at the end of 2003. However, it did produce three game-focused technologies: a Java binding for OpenGL called JOGL, a binding for OpenAL (a 3D audio library) called JOAL, and JInput.

Part of the 2001 initiative was the creation of the JavaGaming.org web site (http://www.javagaming.org), initially manned by volunteers. In 2003, the Game Technology Group was formed, and JavaGaming.org received a substantial makeover as part of the creation of the new java.net portal (http://www.java.net) aimed at the technical promotion of Java. Java.net hosts many discussion forums, user groups, projects, communities, and news. The communities include: Java Desktop, Java Education and Learning, Java Enterprise, and Java Games.

The Java Games community pages can be accessed through http://www.javagaming.org or http://community.java.net/games/. The site includes Java games forums, projects, news, weblogs, a wiki (http://wiki.java.net/bin/view/Games/WebHome), and links to games affiliates.

Numerous Java game forums can be accessed from http://www.javagaming.org/cgi-bin/JGNetForums/YaBB.cgi. These are probably the best sources of technical advice on Java gaming on the Web, with over 4,500 opinionated registered users. Discussion topics include Java 3D, Java 2D, Java Sound, J2ME, networking, online games development, performance tuning, JOGL, JOAL, and JInput. There are also sections on projects and code examples.

The project sections (https://games.dev.java.net/) mostly concentrate on JOGL, JOAL, and JInput, but the games middleware and games forge sections are wider ranging. The games forge projects include Chinese chess, jbantumi (a strategic game from Africa), and an online fantasy football management system.

The most relevant Java user group for gaming is GameJUG (https://gamejug.dev.java.net/). Its sections include online and downloadable Java games, presentations and articles, lists of Java game programming web sites, and a collaborative web page and mailing list for teachers of Java game programming.

Tip

I’m a former GameJUG president, a role that sounds grander than it really was. The real work was done by David Wallace Croft and James Richards.

Sun’s substantial presence at http://community.java.net/games/ is mostly as a host for community forums and open source projects (or projects with licenses very close to open source). The projects include JOGL, JOAL, JInput, and Java 3D. Sun is relying on community involvement to move these projects forward, since the Game Technology Group is quite small.

One in-house product is a server architecture for massively multiplayer online games, the Sun Game Server, first demoed at the Game Developers Conference in 2004. This focus isn’t surprising since Sun makes its money from selling server hardware. Online multiplayer gaming is a potential growth area for its servers.

Get Killer Game Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.