23

Java

I love coffee, I love tea, I love the Java Jive and it loves me.

—Ben Oakland and Milton Drake

In this chapter:

 Processing is really Java

 If you did not have Processing what would your code look like?

 Exploring the Java API

 Some useful Java classes: ArrayList and Rectangle

 Exception (error) handling – try and catch

 Beyond Processing?

23-1 Revealing the wizard

What is Processing exactly? Is it a programming language? It may seem a bit odd to ask this question at the very last chapter of this book. After all, I’ve dedicated 22 chapters to Processing. Shouldn’t you know what it is by now? The truth, however, is that you have been living under something of a convenient fiction thinking that you are learning Processing. While yes, this is the title of the book, you’ve actually been learning a specific programming language: Java. Processing is really a piece of software with which you write code and a library of functions (ellipse, line, fill, stroke, etc.) for drawing and more. It’s not a language. The language, in fact, is Java, and by pulling back the curtain of Processing, what you will discover is that you have been learning Java all along. For example, in Java, you:

 Declare, initialize, and use variables the same way.

 Declare, initialize, and use arrays the same way.

 Employ conditional and loop statements the same way.

 Define and call functions the same way.

 Create classes the same way.

 Instantiate objects the same way.

Processing, of course, gives you some extra stuff for free (and simplifies some stuff here and there), and this is why it is a great tool for learning and for developing interactive graphics projects. Here is a list of some of what Processing offers that is not as easily available with just plain Java.

 A set of functions for drawing shapes.

 A set of functions for loading and displaying text, images, and video.

 A set of functions for 3D transformations.

 A set of functions for mouse and keyboard interaction.

 A simple development environment to write your code.

 A friendly online community of artists, designers, and programmers!

23-2 If you did not have Processing, what would your code look like?

In Chapter 2, I discussed the compilation and execution process — this is what happens when you press the play button and turn your code into a window with graphics. Step 1 of this process involves “translating” your Processing code into Java. In fact, when you export to application, this same process occurs and you will notice in the source folder that along with the file “SketchName.pde,” a new file will appear named “SketchName.java.” This is your “translated” code, only translation is somewhat of a misnomer since very little changes. Let’s look at an example:

u23-01-9780123944436

Exporting the sketch, you can open up the Java file and look at the Java source.

u23-02a-9780123944436u23-02b-9780123944436

It’s clear that little has changed; rather, some code has been added before and after the usual setup() and draw() functions.

 Import Statements — At the top, there are a set of import statements allowing access to certain libraries. You have seen this before when using Processing libraries. If you were using regular Java instead of Processing, specifying all libraries would always be required. Processing, however, assumes a base set of libraries from Java (e.g., java.io.File*) and from Processing (e.g., processing.core.*), which is why you do not see these in every sketch.

 public — In Java, variables, functions, and classes can be public or private. This designation indicates what level of access should be granted to a particular piece of code. It’s not something you have to worry much about in the simpler Processing environment, but it becomes an important consideration when moving on to larger Java programs. As an individual programmer, you’re most often granting or denying access to yourself, as a means for protecting against errors. You encountered some examples of this in Chapter 22’s discussion about encapsulation.

 class JavaExample — Sound somewhat familiar? Java, it turns out, is a true object-oriented language. Everything written in Java is part of a class! You are used to the idea of the Zoog class, Car class, PImage class, and so on, but it is important to note that the sketch as a whole is a class, too! Processing fills this stuff in for you so you do not have to worry about classes when you are first learning to program.

 extends PApplet — Well, after reading Chapter 22, you should be quite comfortable with what this means. This is just another example of inheritance. Here, the class JavaExample is a child of the class PApplet (or, equivalently, PApplet is the parent of JavaExample). PApplet is a class developed by the creators of Processing and by extending it, the sketch has access to all of the Processing goodies — setup(), draw(), mouseX, mouseY, and so on. This little bit of code is the secret behind how almost everything works in a Processing sketch.

Processing has served you so well because it eliminates the need to worry about the above four elements, all the while providing access to the benefits of the Java programming language. The rest of this chapter will show how you can begin to make use of access to the full Java API. (You briefly began this journey when you worked with string parsing in Chapter 17 and Chapter 18.)

23-3 Exploring the Java API

The Processing reference quickly became your best friend forever while learning to program. The Java API will start off more as an acquaintance you bump into from time to time. That acquaintance might turn into a really excellent friend someday, but for now, small doses will be just fine.

You can explore the full Java documentation by visiting:

http://www.oracle.com/technetwork/java/index.html

There, you can click over to API specifications:

http://www.oracle.com/technetwork/java/api-141528.html

and find a selection of versions of Java. While most machines will likely have a version of Java installed, Processing includes Java in the application itself (at the time of this writing, Java version 1.8.0_31). While there are differences between versions of Java, for your purposes they will not be terribly relevant, and you can look at the API for Java 1.8. See Figure 23-1.

And so, very quickly, you will find yourself completely lost. And that is OK. The Java API is huge. Humongous. It’s not really meant to be read or even perused. It’s really purely a reference, for looking up specific classes that you know you need to look up.

For example, you might be working on a program that requires sophisticated random number generation beyond what random() can do, and you overheard a conversation about the class Random and thought “Hey, maybe I should check that out!” The reference page for a specific class can be found by scrolling down the “All Classes” list, or else by selecting the right package (in this case the package java.util). A package, much like a library, is a collection of classes (the API organizes them by topic). The easiest way to find a class, though, is to just type the name of the class and Java (i.e., “Java Random”) into google. The documentation page is just about always the first result. See Figure 23-2.

f23-02-9780123944436

Figure 23-2

Just as with the Processing reference, the Java page includes an explanation of what the class does, the constructors for creating an object instance, and available fields (variables) and methods (functions). Since Random is not imported already, Processing imports by assumption, you do not need to explicitly write an import statement referencing the java.util package to use it.

Here is some code that makes a Random object and calls the function nextBoolean() on it to get a random true or false.

Example 23-1

Using java.util.Random instead of random()

u23-03-9780123944436

in23-01-9780123944436Exercise 23-1: Visit the Java reference page for Random and use it to get a random integer between 0 and 9. http://docs.oracle.com/javase/8/docs/api/java/util/Random.html.

23-4 Other useful Java classes: ArrayList

In Chapter 6, you learned how to use an array to keep track of ordered lists of information. You created an array of N objects and used a for loop to access each element in the array. The size of that array was fixed — you were limited to having N and only N elements.

There are alternatives. One option is to use a very large array and use a variable to track how much of the array to use at any given time (see Chapter 10’s rain catcher example). Processing also offers expand(), contract(), subset(), splice() and other methods for resizing arrays. It would be great, however, to have a class that implements a flexibly sized array, allowing items to be added or removed from the beginning, middle, and end of that array.

This is exactly what the Java class ArrayList (also found in the java.util package) does.

The reference page is here: http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html.

Using an ArrayList is conceptually similar to a standard array, but the syntax is different. Here is some code (that assumes the existence of a class Particle) demonstrating identical results, first with an array, and second with an ArrayList. All of the methods used in this example are documented on the JavaDoc reference page.

u23-04-9780123944436

Perhaps the strangest new syntax here is the declaration of the ArrayList itself. Typically when you declare an object (like PImage) you say simply the data type and the variable name:

PImage img;

With an ArrayList, however, you can say both the data type of the thing itself (ArrayList) and the data type of what you will store inside!

u23-05-9780123944436

While it’s not technically required to specify the data type of what you intend to put in the ArrayList in advance, doing so simplifies the code you’ll write later when using the ArrayList. For example, it opens up the possibility of an “enhanced loop.”

for (Particle p : particles) {

 p.run();

}

Let’s translate that. Say “for each” instead of “for” and say “in” instead of “:”. Now you have:

“For each Particle p in particles, run that Particle p!”

This style of loop (sometimes referred to as “for each”) is a feature of many programming languages and arrived in Java version 1.5. This type of loop can also be used with regular arrays and only recently starting appearing in Processing examples. For simplicity I did not introduce this style of loop in Chapter 9, but now is a good time to go back and revisit.

in23-01-9780123944436Exercise 23-2: Rewrite any of the Chapter 9 examples using an enhanced loop.

What I’ve done so far by simply using a fixed size of 10 has not unlocked the power of the ArrayList. The Following is a better example that adds one new particle to the ArrayList with each cycle through draw(). I also make sure the ArrayList never gets larger than 100 particles. See Figure 23-3.

f23-03-9780123944436

Figure 23-3

The term “particle system” was coined in 1983 by William T. Reeves as he developed the “Genesis” effect for the end of the movie, Star Trek II: The Wrath of Khan.

A particle system is typically a collection of independent objects, usually represented by a simple shape or dot. It can be used to model types of natural phenomena, such as explosions, fire, smoke, sparks, waterfalls, clouds, fog, petals, grass, bubbles, and so on.

Example 23-2

Simple particle system with ArrayList

u23-06-9780123944436

Before you move on I’d like to look at one other scenario where the ArrayList class is useful. In Example 9-8, I looked at how to store a history of mouse locations using two arrays, one for x-values and one for y-values.

int[] xpos = new int[50];

int[] ypos = new int[50];

I made this example before looking at arrays of objects, but with all that you now know I can make a couple of key improvements. The first one is that I can simplify and use a single array. After all, if I had a Point class that stored an x and y then all I need is an array of Point objects.

class Point {

 float x;

 float y;

}

Point[] positions = new Point[50];

In fact, to implement this I don’t even need to create a Point class. This sort of scenario comes up so often that Processing includes a built-in class for this very purpose: PVector. To make a PVector object I simply pass an x and y into the constructor.

u23-07-9780123944436

I can then access the invididual x and y components of a PVector using the dot syntax.

ellipse(mouse.x, mouse.y, 16, 16);

In terms of the scope of this book, I’m going to stop here in the discussion of vectors and the PVector class. A full explanation and discussion of vectors and their various applications can be found in The Nature of Code (http://natureofcode.com) book which is freely avaialable online.

For us, the key here is that once I have an object to store an (x,y) position, I can then use an ArrayList to store a history of those positions.

u23-08-9780123944436

I can add a mouse position to the ArrayList.

u23-09-9780123944436

And I can also remove old entries if the list gets too big.

u23-10-9780123944436

Here’s how the full Snake example now looks using an ArrayList of PVector objects.

u23-11-9780123944436

Figure 23-5

Example 23-3

Store the mouse history as ArrayList of PVector objects

u23-12-9780123944436

in23-01-9780123944436Exercise 23-4: Revise the particle system example so that each particle stores a history of its locations in an ArrayList of PVector objects. What kinds of trails can you draw given this addition? (You might also consider storing each particle’s position and speed as vectors also. For more about how this works, take a look at Chapter 1 of the Nature of Code book (http://natureofcode.com/book/chapter-1-vectors).)

Here’s one last tidbit about resizable arrays before I move on. You might have noticed that none of my ArrayList examples use a list of integers, floats, or strings. While I could use an ArrayList to keep track of these data types, Processing includes three additional classes that I briefly mentioned in Chapter 18. IntList, FloatList, and StringList precisely for this purpose. These lists are internally more efficient than an ArrayList and a bit easier to deal with since you don’t have to worry about maintaining the data type. They also let you sort the lists (ascending/descending) without having to dive into the Java Collections class. I would suggest that any time you’d want to use ArrayList for numbers or text, you’re better off with Processing’s lists.

23-5 Other useful Java classes: Rectangle

The second helpful Java class I will examine is the Rectangle class:

http://docs.oracle.com/javase/8/docs/api/java/awt/Rectangle.html.

A Java Rectangle specifies an area in a coordinate space that is enclosed by the Rectangle object’s top-left point (x,y), its width, and its height. Sound familiar? Of course, the Processing function rect() draws a rectangle with precisely the same parameters. The Rectangle class encapsulates the idea of a rectangle into an object.

The Java Rectangle class includes useful methods, for instance, contains(). contains() offers a simple way of checking if a point or rectangle is located inside that rectangle, by receiving an x and a y and returning true or false, based on whether that (x,y) point is inside the rectangle or not.

Here is a simple rollover implemented with a Rectangle object and contains(). See Example 23-4.

Example 23-4

Using a java.awt.Rectangle object

u23-14-9780123944436
u23-13-9780123944436

Figure 23-6

Let’s have some fun and combine the particle system example with the rollover. In Example 23-5, particles are made every frame and pulled down by gravity toward the bottom of the window. If they run into a rectangle, however, they are caught. The particles are stored in an ArrayList and a Rectangle object determines if they have been caught or not. (This example contains answers to Exercise 23-3 on page 513.)

Example 23-5

Super fancy ArrayList and rectangle particle system

u23-16a-9780123944436u23-16b-9780123944436

Exercise 23-3

Rewrite Example 23-2 so that particles are removed from the list whenever they leave the window (i.e., their y location is greater than height). Note that you cannot use the enhanced loop syntax when modifying an ArrayList inside the loop.

in23-01-9780123944436

Hint: Add a function that returns a boolean in the Particle class when the particle leaves the window.

___________ offScreen() {

  if (_____________) {

  return __________;

 } else {

  return false;

 }

}

Hint: In order for this to work properly, you must iterate through elements of the ArrayList backward! Why ? Because when an element is removed, all subsequent elements are shifted to the left (see Figure 23-4).

f23-04-9780123944436

Figure 23-4

for (int i = ____________; i ____________; i____________) {

 Particle p = particles.get(i);

 p.run();

 p.gravity();

 p.render();

 if (________________) {

  _______________;

 }

}

u23-15-9780123944436

Figure 23-7

23-6 Exception (error) handling

In addition to a very large library of useful classes, the Java programming language includes some features beyond what I have covered in this book. I will explore one of those features now: exception handling.

Programming mistakes happen. We have all seen them.

java.lang.ArrayIndexOutOfBoundsException

java.io.IOException: openStream() could not open file.jpg

java.lang.NullPointerException

It’s sad when these errors occur. Really, it is. The error message prints out and the program sputters to a halt, never to continue running again. Perhaps you have developed some techniques for protecting against these error messages. For example:

if (index < somearray.length) {

 somearray[index] = random(0, 100);

}

The above is a form of “error checking.” The code uses a conditional to check that the index is valid before an element at that index is accessed. The above code is quite conscientious and we should all aspire to be so careful.

Not all situations are as simple to avoid, however, and this is where exception handling comes into play. Exception handling refers to the process of handling exceptions, out of the ordinary events (i.e., errors) that occur during the execution of a program.

The code structure for exception handling in Java is known as try catch. In other words, “Try to run some code. If you run into a problem, however, catch the error and run some other code.” If an error is caught using try catch, the program is allowed to continue. Let’s look at how I might rewrite the array index error checking code try catch style.

u23-17-9780123944436

The above code catches any possible exception that might occur. The type of error caught is the generic Exception. However, if you want to execute certain code based on a specific exception, you can, as the following code demonstrates.

u23-18-9780123944436

The above code, nevertheless, does nothing more than print out custom error messages. There are situations where I want more than just an explanation. For example, take the examples from Chapter 18 where I loaded data from a URL path. What if the sketch had failed to connect to the URL? It would have crashed and quit. With exception handling, I can catch that error and fill an XML object manually so that the sketch can continue running.

u23-19-9780123944436

23-7 Java outside of Processing

Here I am, the very last section of this book. You can take a break now if you want. Maybe go outside and have a walk. A little jog around the block even. It will be good for you.

OK, back now? Great, let’s go on.

As I close out this chapter and the book, I will cover one final topic: what to do if and when you decide you want to start coding outside of Processing.

But why would you ever want to do this?

One instance that would merit another programming environment is in the case of making an application that does not involve any graphics! Perhaps you need to write a program that takes all of your financial info from spreadsheets and logs it in a database. Or a chat server that runs in the background on your computer. While both of these could be written in the Processing environment, they do not necessarily need any of the features of Processing to run.

In the case of developing larger and larger projects that involve many classes, the Processing environment can become a bit difficult to use. For example, what if your project involves, say, 20 classes. Creating a Processing sketch with 20 tabs (and what if it were 40? or 100?) can be hard to manage, let alone fit on the screen. In this case, a development environment designed for large-scale Java projects would be better. Since Processing is Java, you can still use all of the functions available in Processing in other development environments by importing the core libraries.

So, what do you do? First, I would say do not rush. Enjoy Processing and take the time to feel comfortable with your own coding process and style before getting yourself wrapped up in the myriad of issues and questions that come along with programming in Java.

If you feel ready, a good first step is to just take some time browsing the Java website (http://java.sun.com/) and start with one of the tutorials (http://docs.oracle.com/javase/tutorial/). The tutorials will cover the same material found in this book, but from a pure Java perspective.

The next step would be to just try compiling and running a “Hello World” Java program.

public class HelloWorld {

 public static void main(String[] args) {

  System.out.println(“Hello World. I miss you, Processing.”);

 }

}

The Java site has tutorials which explain all the elements in a Hello World program, as well as provide instructions on how to compile and run it on the “command line.”

http://docs.oracle.com/javase/tutorial/getStarted/application/index.html

Finally, if you are feeling ambitious, go and download Eclipse:

http://www.eclipse.org/

Eclipse is a development environment for Java with many advanced features. Some of those features will give you a headache and some will make you wonder how you ever programmed without Eclipse. Just remember, when you started with Processing in Chapter 2, you were probably up and running with your first sketch in less than five minutes. With something like Eclipse, you could need a much longer time to get started. See Figure 23-8.

f23-05-9780123944436
Figure 23-8 A Processing sketch in Eclipse

Visit this book’s web site for links and tutorials about how to run a Processing sketch within the Eclipse environment.

Thanks for reading. Feedback is encouraged and appreciated, so come on down to http://learningprocessing.com and sound off!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.93.210