BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage Articles Teaching Kids Java Programming

Teaching Kids Java Programming

Twelve years ago my younger son Dave showed up in my office holding my Java tutorial. Dave asked me to teach him programming so he could create computer games. By that time I had already written a couple of books on Java and taught multiple classes on computer programming, but those were for grown-ups; Amazon didn’t have any books about programming suitable for kids. After spending hours on Google I could only find some basic attempts to create Java courses for kids, or very basic reader-rabbit-style books. So I decided to write a book by myself.

At that time my older son Yuri was a college student majoring in classical animation, and he agreed to create illustrations for the book. When the drafts were ready, none of the publishers wanted to print it for two reasons:

  • There was no market for programming books for kids.
  • I wanted this book to be printed in color, which was a lot more expensive than black and white.

No big deal. I posted the PDF version online so people could download it for free. A year later some good parents from France translated it to French, and then Java enthusiasts from Eastern Europe translated it to Russian and Ukraninan. These versions of the book are still available online for free download.

Earlier this year I got an unexpected email from No Starch Press publishers - would I be interested in writing a book on Java programming for kids? I asked again, "Would you be willing to print this book in color?" To my surprise the publisher agreed right away showing me a bunch of their books for kids about programming in other languages. Times change… To make a long story short, I accepted. Fast-forward one year, the book should be going to print in the spring of 2015.

Is Java a Good Choice for Teaching Kids?

To answer this question we first need to define the word "kid". For a child under 12, I believe Java may be too complicated as a first programming language; younger children may be better off working with tools for creating visual programs from large prefabricated building blocks. MIT created Scratch, which is a good tool for eight year olds to ignite their interest to explore programming. 10 year olds may go further and start learning actual programming in Java using Greenfoot.

But in my opinion, any 12+ year old interested in learning programming can start learning serious Java programming with the tools that professional developers use. In my original book for kids I used the Eclipse IDE, but for the new book I’ve chosen IntelliJ IDEA Community Edition, which is also available for free.

The difference between teaching Java to kids and adults is that kids respond better when writing GUI programs, and Java is well equipped for this. I’m talking about JavaFX now; the Swing framework is getting old and you really need a professional to create something fancy in Swing, whereas JavaFX offers good tooling and a clean separation between the GUI and application logic.

JavaFX comes with "Scene Builder", a visual GUI designer that generates GUI written in FXML; an XML-based language that allows creating GUIs in a declarative way. But no worries, kids won’t need to learn to write FXML manually - they just drag and drop UI controls on a canvas and Scene Builder generates the FXML.

Java Educators For Kids

If twelve years ago kids were not overly interested in learning programming, many of them are now (thank you, smart-phones). Times change… Accordingly, there are enthusiasts around the world who spend their time and energy introducing programming to kids. Hats off to Stephan Janssen, creator of the Devoxx4Kids movement that teaches teenagers Java in a creative way. This initiative started in Belgium, but now a dozen countries got on board. Here in the USA, Arun Gupta leads the San Francisco chapter, and Matt Raible runs it in Denver. I’m ready to volunteer my time and run a branch in New York City if some Manhattan-based firm would offer a place to host events for kids.

I applaud Stephen Chin from Oracle who travels the world with a bag full of programmable devices. Earlier this year I attended his presentation "Mary Had a Little Lambda", where he explained Java demoing the code of a pretty complex game. This summer I participated in the JCrete unconference in Greece. While other attendees came with laptops, Stephen brought two dozen hardware kits and ran a workshop where kids programmed a robot to dance Sirtaki using Java.

I’m sure there are other good people around the world who are popularizing Java in the kid’s world. A twenty year old Java language becomes younger every year!

Book Extracts

I appreciate the opportunity to offer the InfoQ readers two extracts from my upcoming book "Java for Kids". In this book I use IntelliJ IDEA Community Edition, an excellent free IDE from JetBrains. The first extract is a gentle introduction to classes and objects. The second one is from the Tic-Tac-Toe chapter. When you teach kids, the more visual the programs they create the better. That’s why I use JavaFX in 5 out of 12 chapters. Readers will create a calculator and two games: Tic-Tac-Toe and Ping-Pong.

Book Extract 1: Classes and Objects

In the real world you see and use various objects, each being of some “kind”, like toy, food, animal, electronics etc. In Java instead of saying a kind of object, we say a class of objects. A class is like a blueprint of an object. Any program that you’ll write will be made up of classes.

Java defines various data types. Some of them are simple, like int, which represents integer numbers. Some of them are more complex; these are the classes. For example the System class, which can be used for things like printing texts on the screen, exiting a program or cleaning computer’s memory.

When you installed Java on your computer, thousands of Java classes were downloaded to your computer. Your Java programs will also consist of classes that can represent objects from the real world. If a class is a data type, an object is a representative of a particular type. For instance, you can see ten dogs on the street, and they all represent the class Dog.

Programmers start working on any application by deciding which Java classes to include in the program and how many objects of each type to create. For example, they can define a class Player in the gaming application and create two object instances of this type.

While programmers talk to each other, they may say "Do something with the class Player" or "Do something with the object Player". We need to learn the difference between the meaning of the words class and object.

Let’s see what Java classes can consist of. The most basic class might have anything inside. Take a look at this class declaration:

class VideoGame {
}

This class is empty - it knows nothing and can’t do anything, because there is no code between the curly braces. From the Java syntax perspective this class is legal, and the compiler won’t complain - there is a valid keyword class followed by its name VideoGame, and the opening curly brace has a matching closing brace. But if our programs are going to do something we need classes that can do stuff. So we must load up our classes with methods and attributes:

  • Methods define actions that a class can perform.
  • Attributes describe various properties of a class.

Let’s fill the class VideoGame with some content. This class may have several methods, which can tell what an object of this class can do: start the game, stop it, save the score, ask for additional lives on Facebook, and so on. This class also may have some attributes (a.k.a. fields): color, price and others. An object that represents the class VideoGame can look like this:

class VideoGame { 

  String color;
  int price; 

  void start () {
     // The code to start the game goes here
  } 

  void stop () {
     // The code to stop the game goes here
  } 

  void saveScore(String playerName, int score) {
     // The code to save score goes here
  }
}

This class has two attributes color and price. The color attribute has the String data type, which is used for storing any text. The price is of a type int for storing integer numbers. The class VideoGame has three methods: start, stop, and saveScore. These are the actions that our video game should perform. At this point each of these methods has just a single line that starts with two slashes //.

If a line starts with two slashes, it contains a single line comment - just the description of a code fragment. If you need to write several lines of comments, just type in a slash followed by the asterisk /*, then key in as many lines of a text as you want followed by */ to indicate the end of the comment

We’re not actually going to create a video game yet since you’re just starting to program. But later in the book we’ll develop Tic-Tac-Toe and Ping-Pong games.

But wouldn’t you agree that all games have something in common? With any game you should be able to have a way to start and stop it or to save the score. When you write a program in object-oriented style, start thinking about the bare minimum of attributes or methods you want to put in a class. Then you’ll be able to write another class based on the first one adding more specific features – you’ll learn how to do it later in this chapter in the section about inheritance. That’s the reason why the class VideoGame has only fields and methods that are common to all games.

Figure 1. The Video Game Object

Classes vs Objects

In this section I’ll show you how to create instances of objects based on classes and introduce you to the concept of inheritance.

To reuse code that you or someone else has already written, you can create a class that is derived from another class, thereby inheriting all fields and methods from that other class. A derived class is also called a “subclass”, and the class from which the subclass was derived is called a “superclass”.

The following code sample shows the new class PlayStation4 that is inherited from the class VideoGame.

class PlayStation4 extends VideoGame{
   String hardDiskSize;
   // Other attributes and method declarations go here
   // The method shareOnFacebooks checks that the user is logged in.
   // If not, it displays the window containing the message
   // "Please login to Facebook to be able to share your results"
   void shareOnFacebook(){
      // Code to share on Facebook go here
      System.out.println("Hey, Facebook, I got PlayStation4 with " + hardDiskSize);
   }
   void shareOnTwitter(){
      // Code to share on Twitter go here
      System.out.println("Hey, Twitter, I got PlayStation4 with " + hardDiskSize);
   }
}

The words extends VideoGame mean that the class PlayStation4 has a superclass VideoGame. We can also say that PlayStation4 is inherited from the class VideoGame or 'extends' VideoGame, which also means that the code of the descendant (PlayStation4) may use all attributes defined in its superclass (VideoGame) as well as all methods defined in class Videogame (with certain exceptions) as I’ll explain later in the book. Note that even though the class PlayStation4 does not define the fields price and color, or the methods start, stop, saveScore, all of those are still available for all objects of type PlayStation4. They were inherited from VideoGame and there is no need to copy/paste them into the body of class PlayStation4.

When we create an instance of an object we actually create an object in the computer’s memory that’s based on some class declaration. For example the program CreatePlayStation4Objects shown next creates two instances of the class PlayStation4 using the new operator. It declares two variables firstPlayStation and secondPlayStation of type PlayStation4, and each of these variables points at a separate object in memory. Note that the field hardDiskSize has different values (500GB and 1TB) in these objects. The program calls the method shareOnFacebook on the first object and shareOnTwitter on the second one.

public class CreatePlayStation4Objects { 

    public static void main(String[] args) { 

        // create one instance of the PlayStation4 class
        PlayStation4 firstPlayStation = new PlayStation4();
        firstPlayStation.hardDiskSize = "500GB"; 

        // call the method shareOnFacebook on the first instance
        firstPlayStation.shareOnFacebook(); 

        // create another instance of PlayStation4 class
        PlayStation4 secondPlayStation = new PlayStation4();
        secondPlayStation.hardDiskSize = "1TB"; 

        // call the method shareOnFacebook on the second instance
     secondPlayStation.shareOnTwitter();
    }

Running CreatePlayStation4Objects prints the following:

Hey, Facebook, I got PlayStation4 with 500GB
Hey, Twitter, I got PlayStation4 with 1TB 

If a game factory were to produce 10,000 such games, a programmer could say that they created 10,000 instances of the class PlayStation4. The factory description of PlayStation4 relates to an actual game the way that a Java class relates to its instance in memory. The process of building actual games based on this description in the real world game factory is similar to the process of creating instances of PlayStation4 objects in Java in the programming world. But each instance can have something different, like the size of the internal disk in our example.

Figure 2. One Class, Two Instances

Typically a program uses fields and methods of a Java class only after creating the instance of an object . The same with manufacturers - they create thousands of game copies based on the same blueprint. Even though these copies represent the same class, they may have different values in their attributes - some of them are black, while others can be silver. Some of them have 500GB hard disk dive, while some have 1TB.

Book Extract 2: Changing Styles and Applying Effects

This is an extract from Chapter 10, and by this time the readers already learned the basics of JavaFX, created a sign-in window and a calculator, and know how to apply CSS to style the GUI. The basic Tic-Tac-Toe functionality is already implemented too, but it would be nice to make the winning three-in-a-row combination stand out.

Highlighting the Winning Combination

The styles of the winning buttons should be changed dynamically (during the runtime). First of all, we need to add a style for displaying the winning X-O buttons to the CSS file. Then the class Controller can invoke the method setStyle on the buttons, providing the name of the winning style.

I want to change the background of the winning buttons, however this time I won’t use just a single color, but rather a color gradient. In computer graphics color gradients refer to filling the area with a blend of colors that smoothly transition from one color to another. The color transitioning can be linear or radial, and this Wikipedia article gives you some examples of both.

We’ll use radial gradients in our game. With gradients you can use two or even more colors. Let’s use three colors in the gradient for the winning squares. The background color will transition from white to light yellow, and then to lawn green. We’ll use red for the text of the label on the winning square.

To dynamically change the style of a GUI component you can call the method setStyle and specify the color as an argument, for example:

myButton.setStyle("-fx-text-fill: red;"); 

But embedding CSS rules in your Java program is not a good idea. What if you decide to change the styling (e.g. change the color from red to pink)? You don’t want to search for all places in your Java where this style was used. Besides, changing the styles in the code would require you to recompile your Java program, and who wants to do that for such a simple change! It’s much better to keep the style definitions in the external CSS file, and modify its content as needed.

So far we’ve been using CSS type selectors that can change the style of the specified component types. But CSS allows you to define and name a style that’s not intended for a specific component type and can be applied by name to various components. In CSS such styles are called class selectors. Let’s add a style selector called .winning-square to the file tictactoe.css.

.winning-square {
    -fx-text-fill: red;
    -fx-background-color: radial-gradient( radius 100%, white, lightyellow, lawngreen);
}

The style selector .winning-square includes two style rules: one to set the button’s text color to red, and another to set the button’s background color to our radial gradient. Our Java program has to get a reference to the existing styles of the button and add a.winning-square, which will override both the text and the background color of the button.The method highlightWinningCombo will look like this:

private void highlightWinningCombo(Button first, Button second, Button third){
    first.getStyleClass().add("winning-square");
    second.getStyleClass().add("winning-square");
    third.getStyleClass().add("winning-square");
}

Try playing the game after adding the methods find3InARow and highlightWinningCombo to the class Controller. The winning combination will look as follows:

Figure 3. We’ve got the winner!

JavaFX includes various visual effects and transition based animations that can make your GUI more fun to use.

To use the effect or animation you need to pick one from the package javafx.scene.effect or javafx.animation respectively. I’ll show you how to apply a fade transition the FadeTransition to our winning buttons. Each winning button will keep fading and coming back to its original state. We’ll add the method applyFadeTransition to the Controller class:

private void applyFadeTransition(Button winningButton) { 

  FadeTransition ft = new FadeTransition(Duration.millis(1000), winningButton); 

  ft.setFromValue(1.0);
  ft.setToValue(0.1);
  ft.setCycleCount(10);
  ft.setAutoReverse(true);
  ft.play();
}

This code creates an instance of the animation class FadeTransition that will span 1000 milliseconds (which equals 1 second) and assigns this animation to the winning button. Then the code sets the fading parameters to change the opacity of the button from 1.0 to 0.1 (changing to 0.0 would make the button completely transparent).

Setting the style count to 10 plays the animation 10 times. Because of setAutoReverse(true), the animation will proceed forward on the first cycle, then reverses on the second cycle, and so on. The method play starts the animation. Adding the following three lines to the method highlightWinningCombo will play the animation on the winningButton component.

applyFadeTransition(first);
applyFadeTransition(second);
applyFadeTransition(third);

The screen shot below should give you an idea of how the end of the animation cycle will look like.

Figure 4. Faded winning buttons

Compare this image with the previous one, or better yet, run the code that comes with the book to see the animation in action.

More Reading

I hope that after reading this article some of you are eager to start teaching your kids Java. I’ve got good news for you. The publisher let me post early unedited drafts online so we could collect some feedback from the community before the book goes to print. You may run into some missing commas or other syntax issues, but they’ll be fixed by the book editors by the time it goes to print.

I’m publishing book code samples on GitHub as they become available. If you’ll run into bugs in the code sample or know of a better solution please let me know.

Teach your kids Java! Enjoy Java with your spouse! Introduce Java to you parents too!

About the Author

Yakov Fain is a Java Champion and co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. He leads the Princeton Java Users Group and New York City Dart Users Group. Recently Yakov co-authored the book "Enterprise Web Development" (O'Reilly). Two of his books will be published in 2015: "Java For Kids" (No Starch Press) and the second edition of "Java 24-Hour Trainer" (Wrox).

Rate this Article

Adoption
Style

BT