In this laboratory session you will begin reading Java programs and writing your own Java programs. The goals of this laboratory are to
String
class, one of the core Java classes;
and
int
and double
data types,
two of Java's primitive data types.
Your instructor will tell you which of the proposed experiments you are to perform.
Because each computer system is structured differently, your instructor will supplement this laboratory session with guidelines for compiling and executing programs in your environment.
Prerequisite skills:
Required files:
Optional applet files:
Many people begin working in a new programming language by writing
a short program that prints the words ``Hello World
''.
Here's one such program,
written in Java.
import SimpleOutput; /** * A simple Java program that illustrates textual output. * * @author Samuel A. Rebelsky * @version 1.1 of March 1998 */ public class HelloWorld { /** * Print the string "Hello world." to standard output. */ public static void main(String[] args) { // The object we're using to print output. SimpleOutput out = new SimpleOutput(); // And print out.println("Hello world"); } // main(String[]) } // class HelloWorld
Let's examine the pieces of this program.
The import
statement
import SimpleOutput;
This statement tells the Java compiler that we'll be using one or more
SimpleOutput
objects to support our program. The name of
that class suggests that we will be using the objects to print output
(to the screen or elsewhere).
Introduction
/** * A simple Java program that illustrates textual output. * <p> * Copyright (c) 1998 Addison Wesley Longman. All rights reserved. * * @author Samuel A. Rebelsky * @version 1.1 of March 1998 */
These lines are a comment about the program. A comment is a note for the reader of the program (rather than for the computer). Java supports a variety of commenting styles. The preceding comment is an introductory one. Every introductory comment begins with a slash and two stars and ends with a star and a slash. Every class should have an introductory comment that consists of a few-sentence summary of the intent of the class, a blank line, and the author and version (as above).
Class header
public class HelloWorld {
The class header begins the real code. We're defining a class
named
HelloWorld
that can be used anywhere (because it is
public
). The left curly brace begins the definition (or code)
for the class. You'll see a corresponding closing brace later.
What is a class? The notion of ``class'' is one of the central components of object-oriented programming, and classes are used for many purposes. Classes serve as templates to guide the creation of objects. Classes gather methods that provide functionality for objects. Classes can suggest or limit usage.
In this case, the HelloWorld
class is used to gather
methods. In particular, it has a single method, called
``main
''.
Method summary
/** * Print the string "Hello world" to standard output. */
This method summary is another introductory comment. Each component of a program or class (you'll learn more about these components and classes later) should have an introductory comment.
Method header
public static void main(String[] args) {
This header starts a method (also known as a function or procedure)
definition. In particular, we're
defining a method called main
. Every Java program
must have one main function that begins just like this. For now,
we won't worry about why it looks like this; it just does. When
you execute a Java program, execution begins at the start of your
main method. The curly brace begins the code for the main method.
Comment
// The object we're using to print output.
This line shows another way to comment. The earlier comments began with a slash and a star and ended with a star and slash. You can also begin a comment with two slashes and end it with the end of the line. Generally, you use the slash-star comments for longer descriptions (outside of components and classes) and the double-slash comments for shorter descriptions (usually for a few lines of code).
This particular comment indicates that the following line creates and names an object that we'll be using to print output.
Variable declaration and creation
SimpleOutput out = new SimpleOutput();
This variable declaration says that out
refers to a
new object of type SimpleOutput
. SimpleOutput
objects provide mechanisms for writing to the screen.
Output
// And print out.println("Hello world");
This line says to print the string "Hello World". More precisely,
we use this line to call the println
method of the out
object we've just created and to pass it the string "Hello world". Note
that the ordering here is similar to that we'd use if we were talking to
someone, as in ``Sam, write `Hello World' on the board''.
End of method definition
} // main(String[])
This line matches the brace that opened the body of main
. For
every opening brace you write, you'll need a corresponding closing
brace. The comment isn't strictly necessary, but it makes it easier to
read the program. I'd recommend making it a point to comment every end
brace to indicate what you are ending.
End of class definition
} // HelloWorld
This line matches the brace that opened the definition of
HelloWorld
. Again, the comment isn't strictly necessary,
but it makes the program more readable.
Computers typically cannot execute programs written in source text (such as
the Java program above). Before being executed,
these programs must be translated or
compiled into a form the computer can better understand.
Hence, you will need to execute the Java compiler to translate
any Java program to an executable form. The executable form of a Java
program is called a ``class'' file and has the suffix
.class
. For example, if I compile the program
HelloWorld.java
, the compiled program will be called
HelloWorld.class
.
Java differs from many languages in what you do with the translated program. Typically, programs are compiled to machine code, which the computer can then execute directly. In Java, programs are compiled to Java machine code, which ``Java machines'' can execute directly. Most computers cannot directly execute such code. Hence, you must run a Java machine simulator (also known as an interpreter) to execute your Java programs. Why the difference? Because Java provides many features (typically having to do with security) that typical machines do not provide directly.
In Experiment J1.1
you will execute HelloWorld
and consider some
principal issues in Java development.
In Experiment J1.2 you will extend
HelloWorld
.
We've seen how to print output and a sketch of the overall structure of a simple Java program. Now, let's move on to one that also reads input.
import SimpleInput; import SimpleOutput; /** * A simple Java program that illustrates textual input and output. * * @author Samuel A. Rebelsky * @version 1.1 of March 1998 */ public class Greetings { /** * Prompt for the user's name and print a greeting. */ public static void main(String[] args) { // The object we're using to read input. SimpleInput in = new SimpleInput(); // The object we're using to print output. SimpleOutput out = new SimpleOutput(); // The user's name. String name; // Prompt for the name. out.print("What is your name? "); // Get the name. name = in.readString(); // Print a friendly message. out.print("Hello "); out.print(name); out.println(", welcome to the joys of Java."); } // main(String[]) } // Welcome
Again, we'll look at it, line by line (or at least chunk by chunk).
import
statements
import SimpleInput; import SimpleOutput;
Here, we indicate that we're using two different library objects. The first does simple input; the second does simple output.
Introductory material
/** * A simple Java program that illustrates textual input and output. * <p> * Copyright (c) 1998 Samuel A. Rebelsky. All rights reserved. * * @author Samuel A. Rebelsky * @version 1.1 of March 1998 */ public class Greetings {
Again, we begin with an introductory comment that describes the program and
lists author and version. Next is a class header, indicating
that the class is named Greeting
. Finally, we have an
open brace that begins the class.
Introduce main
/** * Prompt for the user's name and print a greeting. */ public static void main(String[] args) {
We begin with an introductory comment describing the purpose of the method. Then we have the method header, which gives the name and some related information. Finally, we have an open brace to begin the definition.
While methods can have many names, the name ``main
''
has particular meaning to Java. In fact, the main
method
is the core of any Java application. Java uses the main
method as the starting place for the program.
You may be wondering about the other parts of the method declaration
(the public
, static
, and such). Unfortunately,
at this stage of your career, you are best served by accepting that
this code is just how you indicate the start of your program. For those
of you who can't wait for more explanation, you can find a basic explanation
in the notes at the end of this section.
Object declarations and initialization
// The object we're using to read input. SimpleInput in = new SimpleInput(); // The object we're using to print output. SimpleOutput out = new SimpleOutput(); // The user's name. String name;
This time, we have three named objects. One will be used for reading input, one for writing output, and one to store the user's name (since we're reading the user's name, we need to store it somewhere).
String
is a special type of class, used to describe
collections of letters and numbers. Strings appear regularly in Java
programs. For example, "Hello world"
is a string (with
eleven characters). When you deal with textual input and output, you
will need strings. Note that we were able to use the type
String
without import
ing it. This is because
strings are built into Java. Note also that we did not use
new
to create a new String
object. This is because we will be getting a string later in the
program, and the method we use to get the string will create the new
string.
Prompt
// Prompt for the name. out.print("What is your name? ");
Note that SimpleOutput
permits you to use both
println
(which includes a carriage return) and
print
(which does not include a carriage return).
Input
// Get the name. name = in.readString();
SimpleInput
provides a number of methods for reading
values. The simplest is readString
, which reads and
returns one line of text.
Output
// Print a friendly message. out.print("Hello "); out.print(name); out.println(", welcome to the joys of Java.");
Again, we print with print
and println
.
Cleanup
} // main(String[]) } // Welcome
As before, we need to close the definitions of main
and
the complete class.
In Experiment J1.4, you will execute
Greetings
and learn about some of the ways that programmers
inadvertently break programs.
In Experiment J1.4, you will extend
Greetings
to read and print additional information.
As you may have noted from the prior example, it can become tedious
to print a sequence of outputs. In that example, we needed separate
calls to the println
method for the greeting, the name,
and the welcome. It would be useful to be able to print all three with
one statement. Fortunately, Java permits you to concatenate
(join) strings together with the plus (+
) operation. For
example, I could rewrite the three lines above as
out.println("Hello " + name + ", welcome to the joys of Java.");
When programming, it is often necessary to store and name values temporarily. In most languages (including Java), we need to create a storage cell for the value, name that storage cell, and store and retrieve values. Such storage cells are typically called variables.
In Java, all variables are typed. That is, you must describe what type
of values are stored within the variables. You might store numbers,
strings, or even objects. In our first program we needed to work with
an object of type SimpleOutput
, so we created a variable
called out
of that type. In subsequent programs, you
will create variables of other types.
Note that we can get the value stored in a variable by using the name
of the variable and we can store values in variables by writing the
name of the variable, an equals sign, and an expression. For example,
we can declare alpha
and beta
to be string
variables with
String alpha; String beta;
We can assign the string "Java"
to alpha
with
alpha = "Java";
We can assign two copies of alpha
to beta
with
beta = alpha + alpha;
Our previous programs worked with text. A great deal of computation uses numbers instead of text. Let's move on to some programs that read and write numbers. Our basic program will prompt for a number and print the square of that number.
import SimpleInput; import SimpleOutput; /** * A simple Java program that illustrates numeric input and output. * * @author Samuel A. Rebelsky * @version 1.1 of March 1998 */ public class BasicComputations { /** * Prompt for a number and print the square of the number. */ public static void main(String[] args) { // The object we're using to read input. SimpleInput in = new SimpleInput(); // The object we're using to print output. SimpleOutput out = new SimpleOutput(); // The value entered. double val; // Prompt for the value. out.print("Please enter a value and I will square it: "); // Get the name. val = in.readDouble(); // Print a friendly message. out.println(val + " squared is " + (val*val)); } // main } // class BasicComputations
This time, we'll only look at the "new" lines (the ones that differ significantly from those in previous programs).
Numeric variables
double val;
You declare numeric variables by writing the keyword
double
and the name of the variable which says that val
is a variable
that stores numbers. You will soon discover that
double
variables store numbers that
include a fractional portion (e.g., 3.5 and 1.2). If you only want
to store integers (numbers without a fractional portion; some people
call these whole numbers), you can use
int
.
Numeric input
val = in.readDouble();
SimpleInput
also supports a readDouble
method that
reads a number. This line says to read a number and store that number
in val
. If you want to read in integer, you can use
readInt
.
Output and computation
out.println(val + " squared is " + (val*val));
This line illustrates one of the oddities of Java (or comes close to illustrating one of those oddities). The meaning of some symbols is context-dependent. Usually, we think of the plus sign as being used to add two numbers. However, as we've already seen, it can also be used to join strings. In this case, it is being used for the latter purpose. Surprisingly, when you add a string and a number, Java automatically converts the number to a string and adds as if they were both strings.
In Experiment J1.5 you will explore numeric input and output, as well as some simple numeric computation.
This section is optional and is intended for classes emphasizing applets or pursuing a simultaneous discussion of applications and applets.
In addition to supporting the standard application model of programming, Java also supports a variant model, known as the applet model. Applets are programs that are designed to be run within other programs. Most often, applets are graphical programs that run within Web pages. In the first lab session, you may have experimented with applets that drew pictures on the screen or animated balls or balloons. In this session, we'll focus on the static applets.
Interestingly, the structure of an applet differs from that of an
application. In particular, applets typically do not contain
constructors or a main
method. You also declare
applets in a somewhat different way than you declare applications.
The following is a small Java applet that prints the words ``Hello World''.
import java.applet.Applet; import java.awt.Graphics; /** * A simple Java applet that illustrates textual output. * * @author Samuel A. Rebelsky * @version 1.0 of June 1999 */ public class HelloWorldApplet extends Applet { /** * Print/draw the string "Hello world". */ public void paint(Graphics paintBrush) { paintBrush.drawString("Hello world", 10, 20); } // paint(Graphics) } // class HelloWorldApplet
You might include this applet in a Web page as follows.
<html> <head> <title>A Sample Applet</title> </head> <body> <applet code="HelloWorldApplet.class" width="400" height="300"> </applet> </body> </html>
As you may have noticed, many things set
HelloWorldApplet.java
apart from
our HelloWorld.java
application:
main
method.
paint
method.
main
has String[] args
as a parameter,
paint
has Graphics paintBrush
as a parameter.
main
is static
,
paint
is not.
HelloWorld
imports SimpleOutput
,
HelloWorldApplet
imports both
java.applet.Applet
and java.awt.Graphics
.
HelloWorld
must declare and create a new
SimpleOutput
object,
HelloWorldApplet
does not declare any variables
and never calls new
.
println
method took only the string to
print as a parameter, drawString
takes two numbers
in addition.
Let's consider these differences. We begin by noting the way in which Web browsers and other things that run applets operate.
init
method, the browser calls
that. Our HelloWorldApplet
does not, so the browser
ignores it.
paint
method and
supplies a Graphics
object. A Graphics
object, like a SimpleOutput
object, is a utility object
that helps you put information on the screen. (Graphics
is a standard object; SimpleOutput
was developed for this
laboratory manual.)
We are now ready to look at the individual parts.
Imported classes
import java.applet.Applet; import java.awt.Graphics;
These statements tell Java that you will be using two helper classes. One,
called Applet
, is part of the standard Java distribution
(specified by java.
)
and is one of the applet classes (specified by applet.
). The other, called
Graphics
, is also part of the standard Java distribution,
and is one of the abstract windowing toolkit classes (specified
by awt.
).
Class header
public class HelloWorldApplet extends Applet
This class header looks a lot like our other class declarations, but
adds the ``extends Applet
''. This new phrase tells
Java that your new class is an applet rather than an application.
Whenever you write an applet, you need to include this phrase.
Method header
public void paint(Graphics paintBrush) {
Many applets paint/draw pictures on the screen. They know when to do so
because the browser calls their paint
method. They use
a Graphics
object (which we call paintBrush
)
to do the actual painting.
Method body
paintBrush.drawString("Hello world", 10, 20);
This statement tells the the Graphics object to draw the string
"Hello world"
ten units from the left of the
applet's drawing area, and twenty units from the top of the
applet's drawing area.
HTML code
<applet code="HelloWorldApplet.class" width="400" height="300"> </applet>
This HTML tag tells the browser to load the applet named
HelloWorldApplet
, which is stored in the file
HelloWorldApplet.class
. The tag gives the applet
a space in the
Web page with a width of four-hundred units and a height of
300-hundred units.
We have neither time nor space here to introduce HTML, the Hypertext Markup Language used for the World-Wide Web. You can use the document above as a template and experiment on your own.
In Experiment J1.6, you will begin your exploration of applets. In Experiment J1.7, you will explore some of the things that can go wrong when you use applets.
Name: ________________
ID:_______________
Required files:
Step 1.
Make a copy of the two required programs,
compile them, and execute HelloWorld
. Record the results.
Your instructor will provide you with information on copying files,
compiling Java programs, and executing compiled Java programs.
Step 2.
Rename HelloWorld.java
as
helloworld.java
(i.e., change the capitalization)
and try to recompile it. Record any error messages you observe.
What do those error messages suggest about Java?
When you have entered your response, rename helloworld.java
to HelloWorld.java
.
The following steps are primarily applicable to command-line development environments, like Sun's JDK.
Step 3.
Remove SimpleOutput.java
(source
code) but keep SimpleOutput.class
(compiled code) and the
two versions of HelloWorld
.
(Your directory or folder should contain only HelloWorld.java
,
HelloWorld.class
, and SimpleOutput.class
.)
Execute HelloWorld
.
Record the results. If the program doesn't work, suggest why not. If
the program continues to work, suggest why.
Step 4.
Make another copy of SimpleOutput.java
(source
code) and delete SimpleOutput.class
(compiled code).
(Your directory or folder should contain only HelloWorld.java
,
HelloWorld.class
, and SimpleOutput.java
.)
Execute HelloWorld
. Record the results. If the program
doesn't work, suggest why not. If the program continues to work,
suggest why.
Step 5.
Compile SimpleOutput.java
.
Delete the line from HelloWorld.java
that reads
import SimpleOutput;
Try to recompile and execute the program. If the program successfully recompiles, suggest why. If it does not, suggest why not.
After entering an answer, you may wish to read the notes on this problem.
Step 6.
Remove SimpleOutput.java
(source code),
SimpleOutput.class
(object code), and
HelloWorld.class
(object code). You should now have only
HelloWorld.java
in your directory or folder. Attempt to
recompile and execute HelloWorld
. If the program
successfully recompiles, suggest why. If it does not, suggest why not.
Step 7.
Make a copy of SimpleOutput.java
. Delete
HelloWorld.class
if it exists. You should now have
SimpleOutput.java
and HelloWorld.java
in
your folder or directory. Try to recompile and execute
HelloWorld
. Does it compile successfully? Did you
expect it to? Did any new files appear in your directory? What does
this suggest about Java?
Required files:
Before you begin,
if you have not done so already, make copies
of SimpleOutput.java
and HelloWorld.java
and compile them.
Step 1. Insert the following lines to
HelloWorld.java
right before the end of the main
method.
out.print("Welcome to Java."); out.println("We hope you enjoy yourself.");
Execute HelloWorld
. Record the output. Is this what you
expected? If not, suggest why not.
Step 2. Recompile HelloWorld.java
and
then execute it. Record the output. Did you get what you expected?
If not, suggest why not.
Step 3. What do the results of the first two steps suggest?
Step 4. What is the difference between
print
and println
?
Step 5. Replace the line in HelloWorld.java
that reads
out.println("Hello World");
with one that reads
println("Hello World");
Recompile and execute the program. What happens? What does this suggest about Java?
If you introduced any errors in this step, repair them.
Step 6. Replace the line in HelloWorld.java
that reads
SimpleOutput out = new SimpleOutput();
with one that reads
SimpleOutput out;
Recompile and execute the program. What happens? What does this suggest about Java? If you introduced any errors, repair them.
Required files:
In case you've forgotten, here is the code for Greetings.java
.
import SimpleInput; import SimpleOutput; /** * A simple Java program that illustrates textual input and output. * * @author Samuel A. Rebelsky * @version 1.1 of March 1998 */ public class Greetings { /** * Prompt for the user's name and print a greeting. */ public static void main(String[] args) { // The object we're using to read input. SimpleInput in = new SimpleInput(); // The object we're using to print output. SimpleOutput out = new SimpleOutput(); // The user's name. String name; // Prompt for the name. out.print("What is your name? "); // Get the name. name = in.readString(); // Print a friendly message. out.print("Hello "); out.print(name); out.println(", welcome to the joys of Java."); } // main(String[]) } // Welcome
Step 1. If you have not already done so, make a copy of
the required programs, compile them, and execute
Greetings
. Record the results.
Step 2. At times, programmers forget to enter the quote that ends a string. Replace the line that reads
out.print("Hello ");
with one that reads
out.print("Hello );
(i.e., remove the ending quotation mark). What difference do you expect this change to make?
Step 3. Attempt to recompile and execute Greetings
.
What happened? Why?
After entering your answers, correct the error.
Step 3. Another common mistake is to leave out semicolons. Replace the line that reads
String name;
with one that reads
String name
(i.e., drop the semicolon). What difference do you expect this change to make?
Step 5. Attempt to recompile and execute Greetings
.
What happened? Why?
After entering your answers, correct the error.
Step 6. Replace the line that reads
out.print("What is your name? ");
with one that reads
out.print("What is your name? ")
(that is, drop the semicolon).
What difference do you expect this change to make?
After recording your answer, attempt to recompile and execute
Greetings
. Explain what happened.
After entering your answers, correct the error.
Step 7. What do your answers to steps 5 and 6 suggest?
Step 8.
Another common mistake is to mistype a variable name. For example,
we might decide to use output
instead of out
.
Change only the line that reads
SimpleOutput out = new SimpleOutput();
to read
SimpleOutput output = new SimpleOutput();
What difference do you expect this change to make?
After recording your answer, attempt to recompile and execute
Greetings
. Explain what happened.
After entering your answers, correct the error.
Step 9.
Yet another common mistake is to forget to end multi-line comments.
Remove the */
that appears just before
public class Greetings {
What difference do you expect this change to make?
After recording your answer, attempt to recompile and execute
Greetings
. Explain what happened.
After entering your answers, correct the error.
Step 10.
Remove the ``*/
'' that appears just before
public static void main(String[] args) {
What difference do you expect this change to make?
After recording your answer, attempt to recompile and execute
Greetings
. Explain what happened.
After entering your answers, correct the error.
Step 11. It is likely that your answers for steps 9 and 10 were different. Can you explain why?
Required files:
Step 1. If you have not already done so, make a copy of
the required programs, compile them, and execute
Greetings
. Record the results.
Step 2. Extend the program to read in some other fact about the user (e.g., a major or home town) and to print out a response to that fact. Before making the changes, write down the new lines of code. After extending the program, you should recompile and execute the program.
If you make mistakes, the Java compiler will print some error messages. Write down any error messages you receive and a possible explanation of those errors.
Step 3. Remove the semicolon after
import SimpleInput;
Try to recompile the program. Record the error messages. Reinsert the semicolon to repair the error you just created.
Step 4. Remove other semicolons from the program and try to recompile. What semicolons did you remove and what error messages did you get? Record the error messages and corresponding semicolons. Repair those errors.
Required files:
Before you begin,
if you haven't done so already, obtain copies of
SimpleInput.java
and SimpleOutput.java
and compile them.
Step 1.
Obtain a copy of
BasicComputations.java
,
compile it, and execute it. Try a variety of inputs (small numbers,
large numbers, positive numbers, negative numbers, things that aren't
numbers) and record the results for each input. What do the results
suggest about Java's treatment of numbers?
Step 2.
After the line that prints the square in
BasicComputations.java
, add lines that read
out.print(val); out.print(" + 1 is "); out.println(val+1);
What do you think this will do? Compile and execute the program to test your hypothesis. Record any discrepancies and suggest why such discrepancies might occur.
Step 3.
Change all the instances of double
to int
. Change readDouble
to readInt
. Recompile the program. Execute the program
and enter the value 2
. Record the output. Execute the
program and enter the value 2.4
. Record the output. What
does this suggest?
Optional applet experiment
Required files:
Step 1.
Make a copy of the two files. Compile HelloWorldApplet.java
.
Load the applet, using whatever technique your instructor specifies.
(You might load it in a browser like Netscape Navigator or Microsoft
Internet Explorer; you might run an application like Sun's
appletviewer.) Describe the output.
Step 2.
In helloworld.html
, change the width of the applet from
400 to 20. What do you expect will happen when you reload the applet?
Step 3.
Reload the applet, using the modified helloworld.html
.
What happened? Explain why.
After recording your answer, restore the width to 400.
Step 4.
Explain how to update this program to print "Hi there!"
rather than "Hello world"
.
Step 5.
Make the change you suggested in the previous step, recompile
HelloWorldApplet
, and run it. If you did not
get the expected results, update your answer to step 4, and
try again.
Step 6. Change the line that reads
paintBrush.drawString("Hello world", 10, 20);
to one that reads
paintBrush.drawString("Hello world", 100, 20);
What effect do you expect this change to have?
Step 7.
Recompile HelloWorldApplet
and run it. What results
did you observe? What do these results tell you about the second
parameter to drawString
?
When you are done, change that parameter from 100 back to 10.
Step 8. Change the line that reads
paintBrush.drawString("Hello world", 10, 20);
to one that reads
paintBrush.drawString("Hello world", 10, 100);
What effect do you expect this change to have?
Step 9.
Recompile HelloWorldApplet
and run it. What results
did you observe? What do these results tell you about the third
parameter to drawString
?
When you are done, change that parameter from 100 back to 20.
Step 10.
What code might you write to print "Hello"
at the
top left of the screen and "Goodbye"
at the bottom
right?
Step 11.
Try including that code in HelloWorldApplet
. Recompile
and run it. If necessary, keep experimenting until you get it right.
Optional applet experiment
Required files:
Before you begin,
if you have not already done so, make a copy of the required files,
compile HelloWorldApplet
, run it, and record the
results.
Step 1. Remove the line that reads
extends Applet
What effect do you expect this change to have?
Step 2.
Attempt to recompile and execute HelloWorldApplet
. What
happens? Explain why.
After you are done, restore the line that reads
extends Applet
Step 3. Remove the line that reads
import java.awt.Graphics;
What effect do you expect this change to have?
Step 4.
Attempt to recompile and execute HelloWorldApplet
. What
happens? Explain why.
After you are done, restore the line that reads
import java.awt.Graphics;
Step 5. Change the line that reads
public void paint(Graphics paintBrush) {
to one that reads
public static void paint(Graphics paintBrush) {
What effect do you expect this change to have?
Step 6.
Attempt to recompile and execute HelloWorldApplet
. What
happens? Explain why.
After you are done, restore the line that reads
public void paint(Graphics paintBrush) {
Step 7.
Make a copy of HelloWorldApplet.java
called
Example.java
. Replace the body of paint
with
paintBrush.drawString("An example applet");
What do you expect to happen when you try
to compile Example.java
? Try to compile it and explain
the error messages.
Step 8.
Replace all the instances of HelloWorldApplet
in
Example.java
with Example
. What do
you expect to happen when you try to compile it? Verify your
answer by trying to compile it.
Step 9.
Hopefully, Example
compiled successfully. Next, make
a copy of helloworld.html
called example.html
.
Run your new applet using example.html
. What happens?
Why?
Step 10.
If you have not already realized that you need to do so, update
example.html
so that it uses Example.class
instead of HelloWorld.class
.
Write a Java program that prints your favorite poem or short piece of verse. If you have no favorite writing, consider using Lewis Carroll's Jaberwocky.
'Twas brillig and the slithy toves
did gyre and gimble in the wabe.
All mimsy were the borogoves
and the mome raths outgrabe.
Write a Java program that asks for a person's name and then prints
the name one time, then two times, then three times, and then four
times. For example, if the user entered William
, your
program would print
William William William William William William William William William William
The following Java program contains a large number of errors. Identify as many as you can by hand and suggest how to correct them. Once you have done so, enter the revised program in the computer and attempt to compile it. Record any errors the compiler reports and attempt to correct those errors. Note that once you have corrected some errors the compiler may then report additional errors.
impart SimpleInpt import SimpleOutput(); /** * A very erroneous program. * * @author Samuel A. Rebelsky * @version 1.0 of March 1998 public class Erroneous ( /** * Do something. */ public void main(String() args) { SimpleInput in = new SimpleInput; SimpleOutput out = old SimpleOutput; double val Out.print("Please enter a number: ); val - in.readdouble(); in.print(val - 1 + " is " + val - 1); { / /main(String[]) }}
What do you think will happen when a user runs the following program
and enters Lewis Carroll
on one line? Separate lines?
import SimpleInput; import SimpleOutput; /** * Illustrate textual input and output. * * Copyright (c) 1998 Samuel A. Rebelsky. All rights reserved. * * @author Samuel A. Rebelsky * @version 1.0 of March 1998 */ public class Namer { /** * Ask for a name and do some funny things with it. */ public static void main(String[] args) { // Set up input and output. SimpleInput in = new SimpleInput(); SimpleOutput out = new SimpleOutput(); // The person's first name String first_name; // The person's last name String last_name; // Get the name out.print("Please enter your full name: "); first_name = in.readString(); last_name = in.readString(); out.println("I will record your name in my database as " + last_name + ", " + first_name + "."); } // main(String[]) } // Namer
Reflect on the previous programs and see if you can design a program that converts Celsius to Fahrenheit. Use the conversion formula
F = C * (9.0/5.0) + 32.0
Begin by designing your program on paper, rather than on the computer! Experience shows that we do much better when we design before coding. At this stage in your career, you should first design on paper, then sketch your code on paper. Only once you've sketched the code should you move to the computer.
Write a program that creates a bar graph for the following fictitious data on Web browser usage:
Internet Explorer 35% Netscape Navigator 40% HotJava 10% Other 10%
Model your output after the following example:
Lines of code in "Hello World" C: **** C (w/comments): ******* Java: ******* Java (w/comments): ********************* Pascal: ****** Pascal (w/comments): ********** Scheme: * Scheme (w/comments): ** | | | | | 1 5 10 15 20
The main
method.
You may recall that a class's main
method is declared
as
public static void main(String[] args)
What does everything mean?
The ``main
'' names the method. Every Java application
needs a main
method. When you execute a Java application,
the Java interpreter knows to start with main
.
The main
method must be public
, which means
that the method can be called by other classes and other objects. Arguably,
something else (the Java interpreter) is calling this class, so it must
be public.
The main
method must be static
, which means
that it is associated with the class as a whole and not just with individual
objects. In general, Java methods are associated with objects, and can
only be used if you've created a corresponding object. Since we don't
always want to create objects for our applications, main
is static
.
The main
method has type void
, which means
that the method does not return a value. Many methods are like
mathematical functions. For example, we might say that a square-root
function (method) returns a number, and a ``make up a nonsense word''
method returns a word. Because our program will not ``return''
values (simply interact with the user), it needs this void
.
The terms in parentheses are the parameters to the method.
Many methods have parameters. For example, a square-root function would
take a number as a parameter, and a ``translate to Pig Latin'' function
might take a word as a parameter. The args
gives us a
name for the parameter. The String[]
says that this parameter
is a list of words (``String
s'' in Java parlance).
Where do these strings come from? Java, at least in part, comes from an environment (Unix) in which programs are typically invoked from a command line (as in DOS). In addition to specifying the name of the program, you can add information that helps the program work. For example, the Unix ``print'' command accepts files to print as parameters and can also accept information on which printer to use. The designers of Java knew that many programmers would need similar capabilities. You won't need those capabilities in your early programs, but you might need them later.
Aren't you sorry you didn't wait?
Experiment J1.1, Step 4.
In some cases, the Java interpreter is smart enough to find related
classes, even without an explicit import
statement.
However, good practice dictates that you use such statements.
[Front Door] [Introduction] [Code]
Copyright (c) 1998 Samuel A. Rebelsky. All rights reserved.
Source text last modified Wed Oct 6 12:35:57 1999.
This page generated on Tue Oct 26 15:40:07 1999 by Siteweaver.
Contact our webmaster at rebelsky@math.grin.edu