Download From Alice to Java - Santa Monica College

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
From Alice to Java
Santa Monica College
Computer Science 3
Java Course
Pack
By Computer Science Faculty – Santa Monica College
1
Introduction
This tutorial is intended for CS 3 students who have learned how to create programs
using Alice (an environment for learning introductory programming techniques) and now
wish to learn how to write programs in Java (the most popular programming language in
the world according to the TIOBE Programming Community Index1 survey of
programming language popularity).
Getting Started with Java
The Java Tutorial - Getting started with Java at website
http://java.sun.com/docs/books/tutorial/getStarted/index.html by Sun Microsystems, Inc.,
the creators of Java, is an excellent introduction to the language. Rather than repeating
that material here (that would be reinventing the wheel) you are encouraged to read it
now.
Nature of Programming and Using Compiler Software
In writing computer programs we give the computer step-by-step instructions on how to
accomplish the task we need done. This step-by-step direction is called an algorithm. An
algorithm must finish in a finite amount of time. Computer programs are simply
algorithms coded in some computer language. You saw these step-by-step instructions in
Alice programs. There when you run the Alice world, it will execute the first statement,
then the second and so on. Alice is a graphical development environment in the sense
that, when you add objects to the Alice world and then you drag and drop the object’s
methods into the code window (or you use functions that return values), behind the
scenes Alice generated some of the code for you. This automatically generated code
(which is invisible to you) is run when you play your Alice world. In Java programming
you will start to write programs on your own without the kind of help that the Alice
environment provided to you incognito. Among the many tools available to write Java
programs is the Notepad2 text editor which allows you to type your Java program and
save it as a text file. We show an example below. Imagine that you wish to say hello to
the world through a Java program. The Java program below can accomplish that.
1
http://www.tiobe.com/tpci.htm
2
Notepad software is available on all Windows XP Operating systems by clicking on Start | All Programs |
Accessories | Notepad
2
Listing 1
public class HelloWorldApp {
public static void main (String [ ] args) {
System.out.println (“Hello, World!”);
} // main
} // HelloWorldApp
After typing above program in a Notepad file you would save it in a file named
HelloWorldApp.java. All Java programs require that .java be used as the file extension.
This is no different from the fact that all Microsoft word files must have an extension doc
or docx. In addition Java requires that file name be same as class name. We do not expect
you to understand all the words in this program at this point. However, by end of this
course pack they will become clear to you.
After writing a Java program and saving it in a file, we need to compile the program.
Compilers are translator programs that scan through the program you typed and check
that the correct syntax has been used in program typing. Notice that you did not have
worry about that with Alice because Alice, being a drag-and-drop graphical environment,
did not let you make a mistake similar to the one you could make when you type a
program with Notepad. If the compiler finds no mistakes in your program, then it will
create a file called a class file that will allow you to run your Java program. Understand
that not all programs need a compiler. Some programming languages (for example
JavaScript) use a different kind of translator program called an interpreter that translates
and runs the program line by line on the fly, without any compilation. Let us talk about
how to use Java compiler a bit more.
How to Use the Java Compiler
You can use Sun’s Java Software Development Kit (SDK) to compile and run your Java
programs. You will use two tools from the kit:
1. javac - the Java compiler. This is used to compile (translate) your Java source
code (.java file) into bytecode (object code).
2. java - the Java interpreter. This is used to run your Java bytecode (.class file)
on the Java Virtual Machine (JVM).
To use the Java SDK, first open a command prompt window as follows:
Start | All Programs | Accessories | Command Prompt
Then navigate to folder where your .java file is. For this you will need to learn how to
navigate to a folder on certain drive through the Command Prompt environment
(formerly known as the DOS environment). The compilation is done using the following
3
syntax. Imagine that your file name is HelloWorldApp.java. Then compilation will be
done using the following syntax:
>javac HelloWorldApp.java
Note: If entering the above command results in the following error message:
'javac' is not recognized as an internal or external
command, operable program or batch file.
then you will need to set the 'path' environment variable as follows:
path=m:\programs\jdk\bin
This assumes you are working in the classroom (B203) or the Programming Lab
(B231).
If there are no compile errors, then you get no output whatsoever. If there are compile
errors, the Java compiler outputs an error message with a line number appended to it.
When your program has no errors you can execute your program using the command
below:
>java HelloWorldApp
If code has no runtime failure, then it will print out the program message or interact with
user as required by the code. For example, the code shown in Listing 1 on previous page
will print out following words on your Command Prompt console
Hello, World!
Let us now compare some features of Java and Alice.
A Comparison of Alice and Java
Since we learn something new (Java) by relating it to something already known (Alice),
we will now review the HelloWorldApp example shown earlier, comparing each Java
feature to its Alice analog.
HelloWorldApp in Alice
Note that Java Style in Color has been selected from the Edit | Preferences menu in
Alice. Adding Java Syntax adds semicolons and curly braces to your Alice code.
4
HelloWorldApp in Java
The source code for similar hello world program in Java is given in Listing 1 above. The
console output for this Java program is shown in Figure below.
5
Based on what we have seen so far we can compare Java and Alice programs as follows:
A Comparison of HelloWorldApp in Alice and Java
Comparison
Alice
Basis
Program
(aka an
The HelloWorldApp program in
application
Alice is a 3D virtual world.
or app, for
short)
An Alice program is created using
the Alice 3D Authoring system, a
graphical development environment
Entering
in which the programmer uses drag
source code
‘n’ drop graphical tools. The only
keyboard entries are for data values,
such as what Alice says.
On the File menu, click Save. Give
your world a meaningful name.
Alice saves your program with an
To save your
A2W (Alice version 2 world)
program
extension. Save your world often,
especially after making a lot of
changes.
classes
In this program we used the
AliceLiddell class from the Local
Gallery.
objects
The objects in this world are
world, camera, light,
ground, and aliceLiddell.
comments
methods
A comment in Alice begins with
//and ends at the end of the line.
This program has two methods -
Java
The HelloWorldApp program in Java is seven
lines of text that define the HelloWorldApp
class.
A Java program is created using a text editor
(e.g., Notepad) or, better yet, a programmer’s
editor that does code coloring. Dreamweaver is
good for this.
On the File menu, click Save. Save your program
with a java extension. The classname and
filename must agree exactly. Thus, the
HelloWorldApp class definition is saved in a
file named HelloWorldApp.java
In this program we used the System class from
the predefined class libraries that are part of Java.
We also defined a class named
HelloWorldApp.
There is one object in this program System.out. It represents the standard output
device on the host computer (usually the display
screen).
Same as in Alice.
This program has two methods - main() and
6
my_first_method() and
say()
println(). main() corresponds to Alice’s
my_first_method() and println()
corresponds to Alice’s say() .
When you run this Alice program, it
When you run this Java program it begins with
Where shall
begins with the first statement in
I begin?
the first statement in main().
my_first_method().
Java source code must be compiled into bytecode
using the javac compiler tool. To do this, at the
command prompt, enter
To compile Compiling is not necessary in Alice.
javac HelloWorldApp.java
The Alice source code is
your
Bytecode is an intermediate portable language,
interpreted, not compiled.
program
not native machine code. javac saves the
bytecode in a file called
HelloWorldApp.class
The javac tool will inform you of any syntax
errors. For each error it will give the line number,
a ^ marker indicating where it detected the
error, and an error message describing the type of
It is impossible to make a syntax
error.
debugging error in Alice. This is one of the
things that make Alice so cool for
syntax
teaching introductory programming
1. Fix the errors by editing your source code
errors
techniques.
(HelloWorldApp.java).
2. Save your source file.
3. Recompile using the javac tool.
To run the
program
Click the Play button.
debugging
runtime
errors
If a runtime error occurs, Alice will
display an Error Dialog box. Fix the
error. Click Play to test your fix.
Use the java launcher tool. At the command
prompt, enter
java HelloWorldApp
This runs the HelloWorldApp.class file on
the Java Virtual Machine (JVM) which
interprets the bytecode.
The java tool will inform you if a runtime error
occurs. It will give the line number and an error
message describing the type of error.
1.
2.
3.
4.
Fix the error by editing your source code.
Save your source file.
Recompile using the javac tool.
Run it again using the java tool to test
your fix.
If the program doesn’t do what you want:
debugging
If the program doesn’t do what you
logic errors
7
want:
1. Change/fix the program.
2. Run it again by clicking the
Play button to test your
changes.
1.
2.
3.
4.
Change/fix the source code.
Save your source file.
Recompile using the javac tool.
Run it again using the java tool to test
your changes.
Simple Graphical Output in Java
We wish to ascertain that you are not too disappointed by the non-graphical nature of our
first Java example where console is used for input and output. Some graphical input and
output is quite easy in Java. We show a simple example in Listing 2 below.
Listing 2
//Save in file HelloWorldGraphic.java
import javax.swing.*;
public class HelloWorldGraphic {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, “Hello, World!”);
} // end main
} // end class
Figure below shows the popup box output from this program.
In Java program shown in Listing 2 we have used a class called JOptionPane. Just
like Alice stores their objects and classes in galleries, Java stores them in packages.
The first statement in Listing 2 , import javax.swing.*; tells compiler that include
the package with name javax.swing into our program where we find class called
JOptionPane. The single line in the main method in Listing 2
JOptionPane.showMessageDialog(null, “Hello, World!”);
8
uses the class JOptionPane and its method showMessageDialog, which has second
argument as “Hello, World!”, which is printed on the popup box from your Java
program. Notice that the sytnax of calling methods in Java is identical to that of
Alice. When Alice Liddell says Hello world, the syntax in your Alice code window
was something like below
aliceLiddell.say (“Hello, World!”); …………..
then you can see that object with name aliceLiddell invokes its say method with
argument “Hello, World!”. In the above two examples, the objects
JOptionPane and aliceLiddell are similar in nature. Both call their methods
(in one case method say() and in other the method showMessageDialog())
and pass to it the string they wish to print or display. In Java, the JOptionPane
object can also be used for getting an input from user. We show simple example
below (Listing 3).
public class HelloWorldGraphic2 //Save in file HelloWorldGraphic2.java
{
public static void main(String[] args)
{
String Name = “”;
Name = JOptionPane.showInputDialog(null,
“Please type your name, and then click on OK”);
JOptionPane.showMessageDialog(null, “Hello “ + Name);
}
}//Listing
3
When above program is compiled and run it first displays an input box shown by
Figure below:
Then I type my name in the inputbox and then click on OK (see Figure below).
9
Upon clicking on OK, the program in Listing 3 pops up the message box shown
below.
The popup box is disposed by clicking on OK. Let us dissect the Listing 3 to
understand some of its components. First line defines a variable called Name which
is of type String and it is initialized to “”, which is a zero length string. Notice that
variables in Java rquire a type before their name. Alice environment allows you to
choose a data type for a variable when you create new variables. If you recall, the
types of variables in Alice were: Number, Boolean, Object, and Other. Similarily
Java has data types, which of course are much more extensive than Alice. The type
string used in Listing 3 define text or string types which is also available in Alice
uder category labeled “other”. The second line in Listing 3 again uses the
JOptionPane class. This time however, it calls a different method –
showInputDialog, with second argument as string “Please type your name, and then
click on OK”. Notice that when second line is executed, the program pops up the
input dialog box inside which user can type their name (see first figure above). Once
user types their name and then clicks on OK, the second popup box says “Hello
Satish Singhal” as it takes the name inputted by the user and appends word “Hello “
before it. The last program line in Listing 3 is similar to the one shown earlier in
Listing 2, except the second argument to method showMessageDialog concatenates
strings “Hello “ and Name using a plus (+) sign. This indicates that you can
combine strings in Java simply using plus sign, as if you are adding two numbers.
Other Data Types in Java
Java has data types other than string. Table below shows various Java data types and their
minimum and maximum ranges. Do not be too overwhelmed by plethora of types Java
10
makes available for you. In the beginning you would only use four main types. These are
char, int, double and boolean.
Type
Size
Minimum Value
(bytes)
char
byte
short
int
long
float
double
boolean
2
1
2
4
8
4
8
1
Maximum Value
Uses Unicode characters. Language dependent.
-128
127
-32768
32767
-2147483648
2147483647
-9223372036854775808
9223372036854775807
+/- 1.4E-45
+/- 4.9E-324
false
+/- 3.4028235E+38
+/- 1.7976931348623157E+308
true
These values are for Windows 9X system. Values can be Java Virtual Machine dependent
for an operating system.
In above table int (short for integer) stores whole numbers. A Java declaration to store
integer would look like below:
int year_of_birth = 1950; // Notice that data type precedes the variable name
When above statement is executed, Java creates a location in RAM with name
year_of_birth, which is 4 bytes in size, and it stores integer value 1950 in it. Recall that
while Alice did not differentiate between whole numbers and fractional ones, Java does.
This is required for better precision and memory management. We would not be able to
store cost of one gallon of gasoline inside an int data type because cost includes fractions.
For such case we would need to make following type of declaration in Java:
double cost_of_gasoline = 3.99;
For better memory management Java also provides two different mechanisms for storing
text data. If one needs to store a single character then it is preferred to use data type char.
However, the multi character text is stored in string data type. Look at the code fragment
below, where a person’s first name, middle initial and last name is stored in three
different variables.
String First = “John”;
Char Middle = ‘Q’;
String Last = “Public”;
The reason for storing the middle initial in a char data type is because while strings can
use tens of bytes of memory, the char uses only two bytes (see Table on previous page).
11
Thus storing single characters in a char data type is more memory efficient. Therefore,
while from user perspective ‘Q’ or “Q” would have same contents, ‘Q’ would use only a
fraction of memory compared to “Q”.
Variable and Identifier Naming in Java
While Alice is very relaxed in naming of variables, Java is strict. Java requires one to
follow following rules for identifier naming.
1. Identifiers must only contain alphabets, underscore ( _ ), digits (0 to 9 ), and a $ sign.
2. An identifier must begin with an alphabet, underscore or $. It cannot begin with a
digit.
3. An identifier cannot contain blank spaces.
4. An identifier cannot be a Java reserved word.
Examples of Valid and Invalid Programmer Created Identifiers:
The Table below gives the examples of valid and invalid identifiers:
Invalid Identifiers/ Comments
A
a1
Sum+var
+ is illegal
student_name
stdntNm
2names
First character
invalid
_aSystemName
_anthrSysNm
Stdnt Nmbr
Contains Space
$class
int
Reserved word
_public
The identifier sum+var violates the rule #1. Identifier 2names violates rule #2. The
identifier Stdnt Nmbr violates the rule #3 and use of int as an identifier violates the
rule #4. Identifiers in left hand column are valid. It is important to use meaningful
identifiers.
Java reserves certain words that are not allowed to be used as identifiers. This is
done because compiler for its functionality assigns special meanings to certain
words and confusion would result, if those words are also used for
variable/identifier naming. The list of Java reserved words is given below.
Valid Identifiers
abstract
continue
goto
package
this
assert
default
if
private
throw
boolean
do
implements
protected
throws
break
double
import
public
transient
byte
else
instanceof
return
try
case
extends
int
short
void
12
catch
final
interface
static
volatile
char
finally
long
super
while
class
float
native
switch
strictfp
const
for
new
synchronized
byvalue
outer
operator
null
Java Reserved words
Operators in Java
Operators are used in computer programs to assign values, do arithmetic, compare
values, and perform logical operations on boolean data. Table below gives a list of
operators in Alice and Java. Table also shows which operators are identical in both
and which ones exist in one and not in other.
Operator Function/Purpose
Java
Alice
Assign value to operand on left
=
set value
Arithmetic
* /
+ * /
+ Modulus or remainder
%
IEEERemainder
Compare contents of two operands for
== !=
==
!=
equality
Comparison or relational operators
< <= > >=
< <= > >=
Logical negation (NOT)
!
not
Logical AND
&&
both a and b
Logical OR
||
either a or b, or both
Compound operators (Combining
+= -= *= /= Do not exist in Alice
arithmetic and assignment into one action) %=
Prefix or postfix increment or decrement
++
-Notice that Java never uses word for operators. This has been done for conciseness.
Since in Alice you never have to type operators, words that can convey meaning
accurately have been used as operators. We show applications of operators that do
not exist in Alice.
Compound Operators
Java provides compound operators to make code writing concise. For example
following operations are identical.
int x = 5;
13
x = x+ 7 ; is identical to x+=7;
Table below shows other compound operations and their expanded counterparts.
Expanded Operation
Equivalent Compound Operation
x = x – 7;
x-=7;
x = x*2;
x*=2;
x= x/2;
x/=2;
x = x%2;
x%=2;
For sake of brevity, we do not discuss the postfix increment and decrement
operators here. However, when you take your first Java class, you will learn them
quickly. The meaning of prefix increment and decrement operators is as follows:
int x = 5;
++x; // Increases current value of x by one. Thus stores 6 in x.

x; // Reduces x by one. Thus current value of x is 5.
Understand that increment or decrement operator do not need an assignment
operator (=) to change to new value. The assignment is implicit in the use of these
operators.
Creating Objects in Java
In order to create objects in Alice all you had to do was to go to object gallery, pick
your object and drag and drop them on your world. Since Java requires you to
write code for every thing, it uses a reserved word to create an object. You have seen
so far that in Java String objects can be created merely by using an assignment
operator. For example the String object Professor created below would contain
“James Geddes”.
String Professor = “James Geddes”;
This short hand procedure, where assignment operator followed by value is enough
to create object is only available to Java Strings. For creation of all other objects,
Java requires using a reserved word new, followed by the name of the class and a
pair of parenthesis with or without arguments. This whole process is called invoking
a constructor. Imagine we write a Java class called Car. This may be done to
simulate the real car objects or to hold data about cars that is stored in a file or in a
database. For sake of simplicity we only use two properties of a real life car, its color
and number of doors. (Every car has a color and doors). The car class can be
written in Java as follows:
Data members
public class Car
{
private String Color;
Constructor
14
Methods
private int number_of_doors;
public Car(String Clr, int doors)
{
Color = Clr;
number_of_doors = doors;
}
public string getColor()
{
return Color;
}
public int getDoors()
{
return number_of_doors;
}
}//Listing
4A
The Car class has two data members: Color, and number_of_doors. The data
members in Java are similar to the properties for objects in Alice. The keyword
private in front of member data types simply means that we cannot access them
directly. Rather we would need to use two get methods getColor and getDoors to
access them. This kind of data hiding by using the keyword private for data
members is a special characteristic of Java, which is added to make software more
secure. This type of security was not needed in Alice because Alice is simply a
vehicle to learn programming, while Java is a full fledged commercial software
generation system. The Car class also has a special method-like member which has
same name as the class and takes a string and an int as arguments. This method-like
member is called a constructor. Notice that constructor does not have a return type.
This behavior is different from two methods that are also part of class Car. The
method getColor has a return type String, whereas the getDoors has an int return
type. You must learn the difference between methods and constructors, namely the
constructor has same name as class name and has no return type. Now we show how
15
1
2
3
4
to create objects in Java and learn their properties. Listing 4B shows a class with
main method that creates object MyCar of type Car.
public class Main
{
public static void main(String[] args)
{
5
Car MyCar = new Car(“Metallic Green”,2);
6
String MyCarColor = MyCar.getColor();
7
int MyCarDoors = MyCar.getDoors();
8
String ColorAndDoors = MyCarColor+ “ color and “

9
MyCarDoors + “ doors.”;
10
JOptionPane.showMessageDialog(null,
11
“My Car has following properties: “ + ColorAndDoors);
12
13
14
}
}//Listing
4B
We discuss the relationship between Listings 4A and 4B using the line numbers in
Listing 4 B. Inside the main method in Listing 4B, the line 6 has the following
statement:
Car MyCar = new Car(“Metallic Green”,2);
This statement creates an object MyCar in which data member Color is set to
Metallic Green and member number_of_doors to 2. The entire expression on right
hand side is called “invoking a constructor”. The relationship between a class and
objects of that class is one that of relationship between a cookie cutter and cookie
itself. Cookie cutter has the outline for the cookie it would cut. Cookie on the other
hand is the concrete product created by the cookie cutter. Class therefore contains
the outline of objects it would create in terms of data members, methods, and
constructors. Object is the concrete form created from a class that would simulate
the real object. The kind of data the class holds is called metadata by software
engineers. Class holds the design elements or rules for creating objects. The actual
constructor call would instantiate that object inside the software.
Also notice that how Java requires a verbose syntax to create objects. The line 6 has
the data type Car followed by the object name on left side of the assignment
expression. The keyword new and call to the constructor are on the right side of the
assignment expression. Lines 7 and 8 get access to data members, Color, and
number_of_doors for object MyCar and store them in local variables MyCarColor,
16
and MyCarDoors respectively. Line 9 & 10 concatenate the strings that I would like
to print for user informing details of object MyCar. In string concatenation, as long
as one expression is string type, all others can be primitive or string types. Thus the
int MyCarDoors is converted automatically to string type, since other expressions
around it (before and after plus sign) are strings. Lines 11 & 12 use a JOptionPane
object and its showMessageDialog method, to print characteristics of object MyCar
as a popup message for the user (See Figure below).
Creating Graphical Objects in Java Using Java Applets
Java Applets were the first major application of Java programming language that
animated web pages. Java therefore was responsible for early revolution in web
development. Almost all Java graphical technology relies on a technique call
inheritance. Inheritance allows an existing class to be used as a springboard for
more refined and developed classes. Graphical objects need to conform to some
basic operating system rules. Therefore, classes that are used in creating graphics
are developed as basic tools in the language library. Programmers then use these
classes as pre-existing widgets to create their own graphical applications. Java has a
class called JApplet that is used as a base class for writing applets. When we say
“using as a base class”, what we mean is that virtually all data and method members
in that class are usable by our class that would extend the base class. All we are
going to do here in terms of showing graphical Java objects is to create a graphical
version of Hello World program using Java applet. Applets do not require
constructors the way stand-alone Java applications do. However, they do need a
method that works similar to a constructor. This method is called init which is short
for initialization. All Java applets also need another method called paint, which
would paint the graphics on the applet when it shows on web page. The basic source
code is shown in Listing 5 below.
1
import java.awt.*;
2
import java.applet.*;
3
4
5
public class HelloWorldApplet extends Applet
{
17
6
// override init( ) method to set background color of screen
7
public void init()
8
9
10
11
{
setBackground(new Color(250,0,100));
}
12
// override paint() method to automatically display information
13
// in the applet’s window
14
public void paint(Graphics g)
15
{
16
// set font, and color and display message on
17
// the screen at position 250,150
18
g.setFont(new Font(“Ariel”, Font.BOLD, 48));
19
g.setColor(Color.blue);
20
g.drawString(“Hello to World from Santa Monica!”,0,150);
21
22
}
}//Listing
5
The first two lines show the Java packages that we need to import as we are using
classes from them in our code. Line 4 shows that our class HelloWorldApplet
extends the Java class Applet which is inside package java.applet. Using keyword
extends in line 4 establishes an inheritance relationship between HelloWorldApplet
class and Java provided Applet class. Another way of saying that is that
HelloWorldApplet class is a child class of Applet class. The init method simply has
one line in this case which sets the background color for the applet. It does that by
calling the setBackground method and passes it a Color object. The Color object is
created by calling its constructor
new Color (250,0,100);
where the numbers inside parenthesis are values of red, green and blue components
of overall color scheme.
The paint method is responsible for painting the applet on the web page that
displays it. It takes a Graphics class object g as an argument and then uses it to set
font, font color, and finally draw the string “Hello to world from Santa Monica!” at
18
location 0 and 150 pixels from top left corner of browser window. The applets are
compiled exactly the way stand-alone applications are, i. e. using the tool javac.
They are however run first by creating an html file and then opening that file using
a web browser. After compiling a file called HelloWorldApplet.class is created. This
file is similar to executable file in Windows program. The following code is typed in
a notepad to build the webpage that would show the Java applet (Listing 7).
<html>
<body>
<applet code=HelloWorldApplet.class width=750 height=300>
</applet>
</body>
</html>
//Listing 7
Most important line in listing 7 is the line with applet tag. This includes the name of
the class file that applet would open when webpage based on code in Listing 7 is
displayed. For applet to work the file HelloWorldApplet.class and html file that has
the code of Listing 7 must be in the same folder. Imagine that code of listing 7 is
typed and saved in a file HelloWorldApplet.html. When you double click on this file
your web browser would attempt to open tjis file and display the applet. The web
broswer may give a security warning similar to the figure below.
The security warning says “To help protect your security, Internet Explorer has
restricted this webpage from running scripts or Activex controls that could access
your computer. Click here for options”. To display the applet you should click on
this message and then click on “Allow blocked content”. That will display a dialog
box shown below.
19
In above box click on yes and then the applet will be shown in the webpage as shown
in the Figure below.
Creating Java applets is an easy way to create interesting java graphics and include
them in WebPages. When you take a full fledged Java class, you will learn more
about Java graphics.
Selection Structures
Computer languages use selection structure to alter the flow of program and make
decisions. At some points in the program the software may need to make a decision so
that it executes one set of code if certain condition is true, or execute an alternate code if
20
condition is false. One example of this is if or if/else structure. You have seen both of
these in Alice which we revisit here.
The if Statement
SelectionApp in Alice shows a
21
SelectionApp in Java
public class SelectionApp {
/* output message “Hello, ____” using command line arg if present;
otherwise, output “Hello, world!” */
public static void main(String[] args) { // args is the array of
command line arguments
if (args.length > 0) { // if there is at least one argument
// greet the user
System.out.println(“Hello, “ + args[0] + “!”); // args[0] is
the first argument
} else { // there are no command line arguments
System.out.println(“Hello, world!”); // greet the world
} // else
} // main
} // SelectionApp
A Comparison of SelectionApp in Alice and Java
Alice
Java
22
command
line
arguments
running the
program
boolean
datatype
if statement
SelectionApp.java
The Repetition Control Structure
The For Statement
RepetitionApp in Alice
23
RepetitionApp in Java
public class RepetitionApp {
// output the song “For He’s a Jolly Good Fellow”
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(“For he’s a jolly good fellow,”);
} // for i
System.out.println(“Which nobody can deny.”);
} // main
} // RepetitionApp
24
A Comparison of RepetitionApp in Alice and Java
Alice
Java
the
increment
operator
for
statement
RepetitionApp.java
Last Modified: 02/22/2008 14:48:57
25