Learn to Program using Alice

The Transition to Java

Learn how to write, compile, and execute a simple Java program that mirrors the behavior of a simple Alice program.  Learn some of the similarities and some of the differences between these two approaches to programming.

Published:  May 1, 2007
By Richard G. Baldwin

Alice Programming Notes # 195


Preface

This tutorial lesson is part of a series designed to teach you how to program using the Alice programming environment under the assumption that you have no prior programming knowledge or experience.

This particular lesson is designed for those students who have mastered Alice and are ready to make the transition into more powerful programming languages such as Java, C#, or C++.

General

One of the main complaints that I read from educators regarding Alice is that because Alice students are not required to type in their programs and suffer the pains of typing errors and syntax errors, they are ill prepared to transition into more powerful languages such as Java, C#, and C++.  While I don't personally believe that to be true, I have decided that it will be worthwhile to give my Alice students a small taste of that pain.

In this lesson, I will teach you how to write two different programs.  One program is written in Alice and the other is written in Java.  Both programs display the current month, day, and year.  My objective is to teach you about the similarities and the differences between these two approaches to programming.

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

Figures

Listings

Supplementary material

Once you have mastered Alice, I recommend that you also study the other lessons in my extensive collection of online programming tutorials.  You will find a consolidated index at www.DickBaldwin.com.

General background information

In order to write, compile, and execute the Java program that I will present in this lesson, you will need to have Sun's Java Development Kit (JDK) installed on your computer.  Any version of the JDK released by Sun during the past five or six years should be adequate for this simple program.

I will assume that your instructor can show you how to access a command-prompt screen that has access to the JDK.

You will also need access to a text editor capable of creating a plain text file.  Although there are many text editors available for free downloading from the web, Windows Notepad will be adequate for this small program provided that either you or your instructor can make certain that the Java source code file that you create has an extension of .java instead of an extension of .txt.

Discussion and sample code

Alice program named Alice0195a.a2w

The source code for this program is shown in Listing 1.

Listing 1. Source code for program named Alice0195a.a2w.

Alice0195a's Code

Created by: Dick Baldwin

world

Events

When the world starts
Do:
world.main ( );

Methods

  public void main ( ) {
    
       // Copyright 2007, R.G.Baldwin
  // Displays month, day, and year for current date.
  // Note: Month begins with 0 for January.
  // Convert to more standard format by adding 1.
  print( ( ( ( 1 + ( getMonthOfYear() ) ) ) .toString() ) );
  print( ( ( getDayOfMonth() ) .toString() ) );
  print( ( ( getYear() ) .toString() ) );
  }

By this point, you should have no difficulty writing and executing this Alice program.  When the program is executed, it produces output similar to that shown in Figure 1.  On the day that I captured the output from the program, it indicated the 30th day of the 4th month in the year 2007.

Figure 1. Screen output from program named Alice0195a.a2w.
4.0
30
2007

Because this program displays the current date, you will get different results when you run this program.

Highlighting points for discussion

Although you should already understand everything in Listing 1, it will be beneficial for us to highlight certain aspects of the Alice code in preparation for a comparison with a Java program.

Automatic creation of objects in Alice

A lot of things happen behind the scenes in Alice.  Without digging deeply into the source code, we can't know exactly how some of those things are actually implemented.  Fortunately, we do understand how they behave and in the end, that is what counts.

When you create a new Alice world, there are four entities that are automatically created with no help from you:

We have good reason to believe that the last three items in the above list are objects because they have properties, methods, and functions that cause them to behave much the same way as objects that you create using classes from the gallery.  However, we never see the classes from which these three objects are created.

Is the world an object?

Many authors will tell you that the world is also an object.  However, because it has different properties, methods, and functions than the other objects and behaves much differently than the other objects, I'm not sure that it really is an object.  However, that doesn't matter because we do understand how it behaves.  Therefore, rather than to refer to it as an object, I will simply refer to it as an entity that has the ability to own properties, methods, and functions.

The skeleton for a world-level method

When you create a new Alice world, the skeleton for a new method belonging to the world is created and named my_first_method.  I elected to rename that method to main in this program to cause it to be more consistent with Java, C#, and C++.

The event named When the world starts

It is unlikely that we will have the time to study events in my classroom course for which this lesson is primarily targeted.  Therefore, suffice it to say that when you click the Play button in the Alice development environment, an event named When the world starts will be fired automatically.

The code in the Events section near the beginning of Listing 1 specifies that when this event is fired, the method named main will be called.  Thus, the method named main will be executed each time you run this Alice program.

Three print statements

The main method shown in Listing 1 consists of some comments followed by three print statements.  Each of the three print statements calls a specific function belonging to the world.  These three functions return the current month, day and year as numeric values.  The code in Listing 1 converts the numeric values that are returned by the functions to text Strings and displays those three text Strings on successive lines as shown in Figure 1.

A zero-based month value

The first function called is named getMonthOfYear.  This function returns the numeric value of the current month considering January to have a value of 0 instead of a value of 1.  I added a value of one to the returned value before displaying it to cause the value to be more consistent with our expectations.  Usually when we display numeric date information, we consider January to be represented by a value of 1 instead of a value of 0.  After adding the value of one, I converted the new value to a string and printed it.

The two remaining function calls

Similarly, the next two statements in main call the functions named getDayOfMonth and getYear to get and display the numeric values that represent those two items respectively.

Then the main method terminates with nothing else to do.

A syntax anomaly

From a syntax viewpoint, it is interesting to note that it is not necessary to specify that functions belong to the world using syntax like the following:

world.getMonthOfYear()

This seems to be an anomaly.  For example, the Events section of Listing 1 shows that in order to call the main method that belongs to the world, you must use the following syntax:

world.main()

Similarly, if you were to define a new world-level method named test, in order to call it, you would have to use the following syntax:

world.test()

Generally the same thing holds true for setting properties that belong to the world.  When you set the values of properties that belong to the world, you must specify that they belong to the world.  Similarly, when you call functions belonging to the light, the camera, the ground, or objects created from classes in the gallery, you must specify the object to which those functions belong.  The ability to omit a specification of the owner seems to apply only to functions that belong to the world.

Java program named Alice0195b.java

The Java source code listing for this Java program is shown in Listing 2.

Listing 2. Source code for program named Alice0195b.java.
/*File Svg18.java,
Copyright 2007, R.G.Baldwin
Simple Java program designed to illustrate a few
fundamental aspects of Java programming.

This program is designed to be compared with the Alice
program named Alice0195a.a2w.
*********************************************************/
import java.util.Date;

public class Alice0195b{
  
  public static void main(String[] args){
    Date dateObject = new Date();
    
    //Display the day, month, and year.
    System.out.println(1 + dateObject.getMonth());
    System.out.println(dateObject.getDate());
    System.out.println(1900 + dateObject.getYear());
  }//end main
  
}//end class Alice0195b

If you compare Listing 2 with Listing 1, you will see a lot of similarities and some major differences.

When the program starts running

With Alice, for example, once you learn how to program with events, you can specify the method that will be called When the world starts (see the Events section of Listing 1).  In addition, once you learn how to program with events in Alice, you can forego the execution of any method when the world starts running and cause the program to simply wait until some other event occurs to do anything.

With Java, you don't have those options.  The method named main always executes when a Java application starts running.  You normally need to place code in the main method to create at least one object if you want the program to do much of anything worthwhile.

Automatic creation of objects and entities

In Alice, the world entity is created automatically when the program starts running.  This is not true in Java.  Except for some very specialized input/output objects that are automatically created when a Java application starts running, you must create all of the objects that your program needs in Java program code.

Creating and destroying objects at runtime

In Alice, you must manually create all of the objects that will be needed by the program during the manual setup effort before the program starts running.  In other words, it is not possible to write Alice program code that will create and destroy objects at runtime.

In Java, on the other hand, all objects are created (and possibly destroyed) at runtime using code that you write into the program.  Once you define a new class (or decide to use an existing class from the class library, which is similar to the gallery in Alice), you create new objects from that class by applying an operator named new to the constructor method for that class. 

The name of the constructor method is always the same as the name of the class.  For example, if it were possible to create objects at runtime in Alice (which it's not), the code to create a new object from the Penguin class might look something like the following:

new Penguin()

Defining new classes

In Alice, the methodology by which you define new classes is somewhat obscure.  In particular, you begin by adding new methods, functions, and/or properties to an existing object.  Then you right-click the object in the object tree and select the save object item in the popup menu that appears.

When you do that, you are not actually saving an object, regardless of the text in the popup menu.  Instead, you are saving a class that defines the characteristics of the object.  Later on, you can create additional objects from that class by selecting Import... in the File menu and specifying the file that contains the class definition.  (It's also possible to add the new class to the gallery if you choose to do so.)

Defining new classes in Java is not obscure at all.  Rather, the definition of a new class is obvious.  We will see one such class definition in the program shown in Listing 2.

Not truly object oriented

As I explained in the first lesson in this series, Alice is not a true object-oriented programming language.  Rather, it is an object-based programming language.  Java, on the other hand, is a true object-oriented language.

You must type the source code

Perhaps the biggest difference that you will notice between Alice and Java will be the requirement to type the source code for your Java programs.  In Alice, you don't have to type anything (other than new method names, variable names, text strings, etc.) and it is not possible to write code containing syntax errors.  In Java, you have to type everything and syntax errors are not only possible, they are likely for beginning students due to simple typing errors as well as the requirement to memorize and use a complex language syntax.

These are just a few of the general differences between Alice and Java.  Now I will compare the Java code in Listing 2 with the Alice code in Listing 1.

Ignore the comments

Everything down to and including the line of asterisks in Listing 2 is a large multi-line Java comment.  This comment is similar to the comments in the Alice program in Listing 1, except that the format is a little different.  You can just ignore the comments in both cases.

Methods and functions in Java
There is no distinction between methods and functions in Java.  They are called methods in Java regardless of whether they do or do not return a value.

An object of the Date class

This Java program will create an object of a class name Date that contains the date and time that the object is created.  Then the program will call methods belonging to that object to display the month, day, and year that the object was created.

Import directives

The line of code in Listing 2 that begins with the word import is called an import directive.  The sole purpose of this directive is to tell the system where to find the file containing the definition of the class named Date.  This is similar but not identical to you telling the Alice development environment where to find or where to store an Alice program.  The main difference is that in Alice, you do that when the program isn't running.  The import directive in Java tells the system where to find a file while the program is running.

The controlling class definition

The line that begins with public class in Listing 2 is the first line in the definition of a new class named Alice0195b.

In Java, all executable code must be inside a class definition.  (Comments and import directive are not considered to be executable code.)  The text for this new class definition extends all the way to the last line in Listing 2.

A class definition in Java always has a name and a body.  The name of the class being defined in Listing 2 is Alice0195b.  The body consists of all of the code between the matching curly braces beginning with the one immediately following the name, and ending with the one at the extreme left end of the last line of text in Listing 2.  (The remainder of the last line of text is simply a comment.)

A Java program can contain many class definitions, but only one will contain a method named main.  I call the class that contains the main method the controlling class but that terminology is by no means universal.

The main method

As mentioned earlier, every Java application must have a main method.  This is a very simple Java program.  The body of the class named Alice0195b consists solely of the main method.  (Although there are a lot of other programming constructs that can be included in the body of a class, they weren't needed for this simple program.)

Also, as mentioned earlier, the main method is always executed first when a Java application starts running.

The method signature

The line that begins with public static is the first line in the definition of the method named main(In Java, this line is often referred to as the method signature.  Also, in Java, the signature of the main method is always the same as that shown in Listing 2, with some allowable minor insignificant variations.)

A name and a body

A Java method always has a name and a body.  In this case, the name is main.  The body consists of everything between the pair of matching curly braces beginning with the one at the far-right end of the signature and ending with the one at the far left end of the second line of text from the end.  The remainder of that line is a comment.

Date and time information

In Alice, date and time information is automatically available by calling functions belonging to the existing world entity.

In Java, if you want to get date and time information, you must create a new object from the class named Date.  If you want to use that object more than once, you must save a reference to the object.  Both of these actions are accomplished by the first statement inside the body of the main method that reads:

Date dateObject = new Date();

A reference variable

The following expression (taken from the left side of the above statement) declares a new variable named dateObject capable of storing a reference to an object created from the class named Date.

Date dateObject

Declaring this variable in Java is similar to clicking the button labeled create new variable while editing a method in Alice and then specifying the name dateObject and the type Object for the new variable in the popup dialog that appears.  You already know how to do that.

Create the new object

The following expression (taken from the right side of the above statement) actually creates the new object of type Date causing it to occupy memory:

new Date()

Saving the object's reference

The assignment operator (=) that joins the two expressions shown above causes the new object's reference to be stored in the variable for later use.

Calling System.out.println

There are three more executable statements in the main method in Listing 2, each of which begins with System.out.println.

Without getting into the details, calling this method in Java is essentially the same as dragging the print tile from the bottom of the Alice development screen and dropping it into an appropriate location in the program edit panel.  Whatever is contained in the matching parentheses to the right of println is displayed on the computer screen.

The Java program output

These three statements produce screen output similar to that shown in Figure 2.  As with the Alice program shown earlier, on the day that I captured the output from the Java program, it indicated the 30th day of the 4th month in the year 2007.

Figure 2. Screen output from program named Alice0195b.java.
4
30
2007

Note the similarity between the Java program output shown in Figure 2 and the Alice program output shown in Figure 1.

Comparison of the Java and Alice programs

The Java code shown in Listing 2 creates a new Date object that contains the current date and time obtained from the system clock when the object is created.  A reference to the object is saved in the variable named dateObject.

The getMonth Java method and the getMonthOfYear Alice function

The first of the last three statements in the main method in Listing 2 uses that reference to call the method named getMonth belonging to the Date object.  As is the case with Alice, this method returns a numeric value for the month with January being represented by the value 0.  Also, as is the case in the Alice code in Listing 1, I added a value of one to the returned value before displaying it to make it more consistent with the way that we like to see the numbers of the month represented.  The resulting month number is shown in the first line of output in Figure 2.

This statement corresponds to the first statement following the comments in the Alice program in Listing 1.  The Alice program calls a method named print whereas the Java program calls a similar method named println.

The Alice program calls a function named getMonthOfYear, whereas the Java program calls a method named getMonth for the same purpose.

The toString function

The Alice print method requires that the material that is to be printed be converted from a numeric type to a text String type before being passed to the method.  That is the reason the toString function is called in the Alice code in Listing 1.

The Java println method is capable of accepting its input as a numeric type and converting it internally to a text String type before displaying it on the screen.  Although Java has a toString method, there was no requirement to call it to perform that conversion in this Java program.

The getDate Java method and the getDayOfMonth Alice function

The next to the last executable statement in the main method in the Java program in Listing 2 corresponds to the next to the last statement in the Alice program in Listing 1.

The Java program calls a method named getDate to get and display the day of the month.  The Alice program calls a function named getDayOfMonth to get and display the day of the month.  These two method/function calls produce the screen output shown in the second line of text in Figure 1 and Figure 2.

The getYear method and function

Finally, the last executable statement in the main method in the Java program in Listing 2 calls the method named getYear to get and display the year.  This Java method returns the year relative to the year 1900.  (For example, it returns a value of 107 for the year 2007.)  Therefore, I added 1900 to the returned value before displaying it in the Java program in Listing 2.  This produced the third line of output shown in Figure 2.

The last statement in the main method in the Alice program in Listing 1 also calls a function named getYear to get and display the year as the third line of output shown in Figure 1.

The code is very similar

As you can see from the above discussion, once the Date object is created in the Java program in Listing 2, the code required to use that object and display the date information is very similar to the code required to use the existing world entity and display the date information in the Alice program in Listing 1.

Lab project

The purpose of this lab project is to give you some experience in:

Why not use an IDE?

Professional Java programmers typically use an Integrated Development Environment (IDE) as a tool to reduce the effort required to accomplish these three steps.  However, for this simple program, we will take the most fundamental approach and totally forego the use of an IDE.

Create your source-code file

Use a text editor such as Windows Notepad to create a text file containing the source code shown in Listing 2.  The comments aren't important, so you can omit them and save yourself some typing effort.  Also, the indentation isn't required, but is commonly used to make the program more readable.  I recommend that you include the indentation.  Otherwise, type the source code exactly as shown in Listing 2.  Even the smallest typing error will often prevent your Java program from compiling and executing successfully.

Save the text file in a file named Alice0195b.java(If you are using Notepad, make certain that the file extension is .java and not .txt.  You may need to ask your instructor to help you with this.)

Accessing the Java Development Kit (JDK)

This lab project assumes that you have access to a computer with Sun's JDK installed.  Ask your instructor to show you how to gain access to a command-prompt screen that has access to the Java software.  The command prompt should be opened in the same directory where you stored your Java source code file named Alice0195b.java.  To make things a little easier later, it might be best to use a directory that is otherwise empty, but that is not a requirement.

Compile your Java program

Execute the following command at the command prompt to compile your program:

javac Alice0195b.java

What happens next?

Depending on the version of Java that you are using, the next thing that you see on the screen should be a new command prompt, or the following two warnings followed by a new command prompt

Note: Alice0195b.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details. 

Either result is okay and probably means that your file compiled properly.  (Don't worry about what the warnings mean.  You will probably learn about them when you enroll in a Java programming course.)

If you see anything else on the screen, that probably means that you made a typing error when creating the source-code file, or something else is wrong.

Confirm a successful compilation

To confirm that your program compiled properly, enter a dir command at the command prompt to list the files in the directory.  That listing should include both of the following files but not necessarily in this order.  (This is where it will be helpful if the directory is otherwise empty.):

Alice0195b.java
Alice0195b.class

The first file listed above is the source-code file that you created with the text editor.  The second file is the file that resulted from compiling the source-code file.  The purpose of compiling the file is to convert it from human-readable (source-code) language to machine-readable language.  If you don't see both of these files, you may need to ask your instructor to help you troubleshoot the problem.

Running your Java program

Assuming that you do see the two files listed above, enter the following command at the prompt to execute your program:

java Alice0195b

The program should display the month, day, and year for the day on which you run the program.  The three values should be displayed on three separate lines as shown in Figure 2.  Once again, if this is not what you see, you may need to ask your instructor to help you troubleshoot the problem.

Congratulations

If that is what you see, congratulations!  You have just typed, compiled, and executed your first Java program.  Other Java programs are essentially the same as this one.  They are simply a lot larger and they involve a much larger number of object-oriented programming concepts in their design than is the case for this simple program.  There is a lot more for you to learn about object-oriented programming using Java and a lot more typing required for larger programs.

Summary

In this lesson, I taught you how to write two different programs.  One program is written in Alice and the other is written in Java.  Both programs display the current month, day, and year.  My objective was to teach you about the similarities and the differences between these two approaches to programming.

Resources

General resources

Resources from earlier lessons in the series titled "Learn to Program using Alice"

Downloads


Copyright

Copyright 2007, Richard G. Baldwin.  Faculty and staff of public and private non-profit educational institutions are granted a license to reproduce and to use this material for purposes consistent with the teaching process.  This license does not extend to commercial ventures.  Otherwise, reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP).  His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments.  (TI is still a world leader in DSP.)  In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-