Lab 03
Lab 03
PURPOSE OF LAB 03
Working with objects is central to programming in an Object – Oriented Language such as Java. In this
lab you will work with
objects that are used to create a Graphical User Interface, or GUI
Strings are used for both input and output in our programs.
TO PREPARE LAB 03
Read Wu: Read Chapters 1 and 2. You may omit the following:
pages 51 – 54 Ch2FunTime.java and Ch2MyWebBrowser.java
pages 66 – 68 Section 2.4.3 Date and SimpleDateFormat (this may be covered in class)
Read through this laboratory session
Using your memory device, create a directory called lab03 in which you should save all of your
work. There are no files to copy for this lab.
TO COMPLETE LAB 03
This is an individual lab. You may get help from other students as well as the lab tutor. Read
the honesty policy for guidelines.
When you have completed the lab,
See the lab tutor, who will give you a 10 point, open note, individual quiz.
For 10 points, hand in to the lab tutor, a printed copy of the final versions of the two
programs in this lab, HelloWorld.java and StringTest.java
When you have finished this lab, see the lab tutor, who will give you an open note,ten - point
quiz. For ten points, hand in printouts of you final versions of HelloWorld.java and
StringTest.java. This will be your grade for Lab 03
I d e n t i f i e r s : Choosing names that indicate the purpose of the class, method or data value is known as
self – documentation .
C l a s s N a m e s : begin with a capital letter, additional words are capitalized. Examples:
First, HelloWorld, JFrame, JOptionPane
v a r i a b l e N a m e s : begin with a lower case letter, additional words are capitalized.
Examples:
myWindow, visible, width, height, interestRate Note: no parentheses
m e t h o d N a m e s : begin with a lower case letter, additional words are capitalized.
Examples:
setTitle(), setSize(), showMessageDialog() Note: always parentheses
C O N S T A N T S : are completely capitalized, additional words are separated with an
underscore character _ . Examples:
PI, MAX_VALUE, INTEREST_RATE
At all times, you are expected to follow the Java guidelines for choosing identifiers.
Failure to do so will result in points being deducted from the code you write.
title
Experiment 1: HelloWorld.java
height in pixels
you, this will be your second program. Instead of printing
to System.out , as done in First.java , the message will be
displayed in a JDialog box that is centered in a JFrame
window. A JFrame object can be displayed on the computer
monitor as a window with characteristics, or data values,
that include height , width and title .
JFrame object
To better understand the code that displays this message, the program will be written in small increments
that can be compiled and executed. Space is allotted for you to record the results of each step.
Step 1: Begin by opening TextPad and enter the code required for all Java applications :
class HelloWorld
{
public static void main(String[] args)
{
}
}
Save the file with the required name HelloWorld.java in your lab02 directory.
Compile the program. Even though there are no statements to execute in the main method, it is a good
idea to compile programs frequently. This way, if an error has been made, it can found more easily.
The statements that are executed when the application is run are placed, in the order they are to be
executed, inside the body of the main method.
Step 2: Add the two new statements to the main method of your program.
class HelloWorld
{
public static void main(String[] args)
{
JFrame frame; // declare a variable of type JFrame
frame = new JFrame(); // create a JFrame object & assign it to frame
}
}
Compile the code. Record the "essence of " the compiler error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
The Java API library of classes is organized into various directories that contain definitions of classes that
have some commonality. The JFrame class is stored in the directory swing , which is a subdirectory of the
directory javax . The compiler must be told where the JFrame class can be found.
S t e p 3 : To correct the compiler error, add an import statement as the first line of code in the file.
import javax.swing.JFrame;
Compile the code and run the program. Record the results
________________________________________________________________________________________________
________________________________________________________________________________________________
S t e p 4 : The instance method setTitle must have a String argument, representing the title to be
displayed in the JFrame object's titlebar.
frame.setTitle("My Hello World Program");
The instance method setSize has two arguments that represent the width and height of the JFrame
measured in a number of pixels.
frame.setSize(500, 500);
Add these two lines of code to the end of the body of the main method, Compile the code and run the
program. Record the results.
________________________________________________________________________________________________
________________________________________________________________________________________________
The JFrame object has an instance variable visible that initially stores false . The JFrame instance
method setVisible must have a boolean argument, either true or false .
S t e p 5 : Add the statement
frame.setVisible(true);
at the end of the body of the method main . Compile the code and run the program. Record the results.
________________________________________________________________________________________________
________________________________________________________________________________________________
N o t e : On a PC, close this program by click on the X in the upper right – hand corner of all open windows.
S t e p 6 : Experiment by changing the integer arguments in the statement that sets the size, in the
number of pixels, of the JFrame object. Each time compile and run the program. Then answer this
question. Which argument (first or second) represents the height of the JFrame object and which
argument represents the width? In you answer indicat how you made this determination.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
There are two arguments that must be passed to the method. frame identifies the parent component on
which the dialog box is centered and the String is the message that is printed.
S t e p 7 : Add the statement above at the end of the main method. In addition, because the JOptionPane
class is also defined in the javax.swing package, add an import statement to the beginning of the file.
Your HelloWorld.java file should now contain the following code:
import javax.swing.JOptionPane;
import javax.swing.JFrame;
class HelloWorld
{
public static void main(String[] args)
{
JFrame frame;
frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("My Hello World Program");
frame.setVisible(true);
JOptionPane.showMessageDialog(frame, "Hello World!");
}
}
Compile the code and run the program. Record the results. Does your program work as expected?
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Syntax Errors
A syntax error occurs when the rules of the language are violated. These errors are always found by the
compiler. The error message is determined by the compiler that is used.
Error 1: Eliminate the first double quote ( " ) in the statement
frame.setTitle(My Hello World Program");
When I made Error 1 and compiled the program on my home PC, I received two error messages for the
single error. Notice, that both error messages found the correct line on which the error was made, but one
states the exact error. In TextPad, to view line numbers in the source file click on View – Line Numbers.
File name line # the error
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Error 2: Correct Error 1. Then, eliminate the second " in the statement
frame.setTitle("My Hello World Program);
Compile the code. Record only the "essence" of either the first or the most informative error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Error 3: Correct Error 2. Then, eliminate the semicolon at the end of the statement.
frame.setTitle("My Hello World Program")
Compile the code. Record only the "essence" of either the first or the most informative error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Error 4: Correct Error 3. Then misspell the word frame in the line
JOptionPane.showMessageDialog(frame, "Hello World!");
Compile the code. Record only the "essence" of either the first or the most informative error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Error 5: Correct Error 4. Then, use incorrect capitalization in the word JOptionPane in the statement
JOptionpane.showMessageDialog(frame, "Hello World!");
Compile the code. Record only the "essence" of either the first or the most informative error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Error 6: Correct Error 5. Then, omit one of the arguments in a method call. Replace the line
JOptionPane.showMessageDialog(frame, "Hello World!");
with the line
JOptionpane.showMessageDialog("Hello World!");
Compile the code. Record only the "essence" of either the first or the most informative error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Runtime errors
A runtime error occurs during the execution, or running, of a program. Basically, the computer is
instructed to do something that it cannot do. Run – time errors cause the program to stop and error
messages to be printed to monitor. For example, if a calculation involves division by zero, a runtime error
message that declares an Arithmetic Exception may be printed in the terminal window.
Error 7: Correct Error 6. Then change the spelling of the word main to Main
public static void Main(String[] args)
Compile the code and run the program. Record any error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Error 8: Correct Error 7. The following error may be a runtime error, or, depending on the compiler, it
may be found by the compiler. Comment out the statement that creates the JFrame object
//frame = new JFrame();
If the code compiles, run the program. Is this error a runtime or compiler error? Record the error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Note: In the future, commenting out lines of code is a very good way to determine where errors are made.
SESSION 2 PAGE 4.8
J A V A L A B M A N U A L
Logic errors
A logic error occurs when the semantics of the code is correct, but the meaning of the code, the semantics,
is incorrect. A logic error is often called a bug. If your program has a bug, it cannot be found by the
compiler or by the computer when the program is run. Instead, it must be found by the programmer or by
a person specifically assigned to test the program. Examples of logic errors are calculations that give
incorrect results and special situations that are not handled or considered. You are expected to carefully
test your programs to be sure that they are free of bugs. Since our program is small, not many logic errors
are possible.
Error 9: Correct Error 8. Then change the spelling of Hello to Hellow
frame.setTitle("My Hellow World Program");
Compile the code. Run the program, if the code compiles. Record any error message.
________________________________________________________________________________________________
________________________________________________________________________________________________
Compile the revised code and run the program. Record the results
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
W
o
r
l
d
!
Record your change to the previous program. Compile and run the program to make sure it works. What
happened to the dimensions of the JDialog box?
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Leave the modified statement in this program as we continue to add more to the program. See the Post-Lab
Exercises for more escape characters.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Run the program a second time. This time click the Cancel button instead. Record the results.
________________________________________________________________________________________________
________________________________________________________________________________________________
Print a copy of this last version of HelloWorld.java and be sure that this
final version is stored on you memory device in the lab03 directory.
Compile the code and run the program. Record the results.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
All methods have a method header, which tells the user how to use the method. The method header
consists of a return type, the name of the method name followed by a set of parentheses surrounding an
optional list of parameters. The parameters, another name for variable, tell the user the number and types
of arguments that must be passed to the method when it is invoked. We will look at these String instance
methods with headers:
In the explanations of the methods that follow, this refers to the object on which the method is invoked.
Therefore, in the statement
word.toUpperCase();
word is this object.
String toUpperCase(): is used to create and return a new String whose letters are equivalent to this
String but are all UPPER CASE letters. No arguments are passed to the method.
Step 2: Add these statements to the end of the main method.
word.toUpperCase();
JOptionPane.showMessageDialog(frame, "You entered " + word);
Compile the revised code and run the program. Record the results
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Step 3: Invoking the method toUpperCase() on a String does not change the existing String , rather, it
creates a new String . Therefore, to change word to its upper case equivalent, the returned String needs to
be assigned to word or to some other String variable.
Compile the revised code and run the program. Record the results
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
S t e p 4 : If we only want to print word in upper case letters, then another option is to invoke
toUpperCase on word in the showMessageDialog method. Remove the statement
word = word.toUpperCase();
and change the statement
JOptionPane.showMessageDialog(frame, "You entered " + word);
to
JOptionPane.showMessageDialog(frame, "You entered " + word.toUpperCase());
Compile the revised code and run the program. Record the results
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
S t e p 5 : Predict what is stored in word after the new statement is executed. Add code to test your
prediction. Record the code that you added.
________________________________________________________________________________________________
int length (): returns the number of characters in this String . No arguments are passed to the
method.
S t e p 6 : Without removing any statements, add to the end of main the statement
JOptionPane.showMessageDialog(frame,
word + " has length " + word.length());
Compile and run the revised program, entering your full name. Record the two printed messages. Was
your prediction in Step 5 correct?
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Every character in a String has an index, or position in the String . The index of the first character is 0,
and the index of the last character is always one less than the length of the String.
int indexOf (String s): expects a String argument and returns an integer representing the index of
the first occurrence of s in the String on which the method is invoked.
M a r q u e t t e
0 1 2 3 4 5 6 7 8
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
2. If the argument is not contained in the object, what index is returned?
________________________________________________________________________________________________
char charAt(int index): An integer argument representing an index into this String , must be
passed to the method. The character at index is returned.
S t e p 9 : Without removing any statements, add the statement
JOptionPane.showMessageDialog(frame,
word + "\n" +
"char at index 0 is " + word.charAt(0) + "\n" +
"char at index 3 is " + word.charAt(3) + "\n" +
SESSION 2 PAGE 4.14
J A V A L A B M A N U A L
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
Run the program one more time. This time enter "Warriors" when prompted for a word. Record what
happens. Can you explain why this happens?
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
String substring (int beginIndex, int endIndex): Two integer arguments representing
indices into this String must be passed to the method. A substring of this String , beginning with the
character at beginIndex and up to, but not including, the character at endIndex is returned.
String substring (int beginIndex): One integer argument representing an index into this String
must be passed to the method. A substring of this String , beginning with the character at beginIndex and
going to the end of this String is returned.
M a r q u e t t e
0 1 2 3 4 5 6 7 8
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
spaces
2. Write a program Pattern.java that prompts the user for a four letter word using an input dialog.
Then, print the following pattern with the word using the substring method and string concatenation. For
example: If the user enters the word "Java", your program should print one of the following in a message
dialog,
A. J B. J
Ja Ja
Jav Jav
Java Java
Jav Jav
Ja Ja
J J
3. Use String methods to write a program called Name.java that prompts the user for his First Middle
Last names in one input dialog. That is, a string such as "Thomas Patrick Jones" will be entered. Use a
message dialog box to print the name Last, First MiddleInitial. Therefore, the string "Jones, Thomas P."
would be printed in a message dialog.
4. Use String methods to write a program called Jumble.java that prompts the user for his First Last
names in one input dialog. That is, a string such as "Thomas Jones" will be entered. Use a message dialog
box to print the first and last names with the first letters interchanged. Therefore, the String " Jhomas
Tomes" would be printed in a message dialog.
5. Use String methods to write a program called TitleCase.java that prompts the user for his First Last
names in one input dialog. That is, a string such as "THOMAS jones" could be entered. Use a message
dialog to print the name in title case, i.e. first letters of each name are capitalized, all other letters are in
lower case. Therefore, the String " Thomas Jomes" would be printed in a message dialog. Note: The
String class contains the method String toLowerCase() which returns the lower case equivalent of the
String on which it is invoked.
6. Use String methods to write a program Reverse.java that prompts the user for a four letter word using
an input dialog. Use a message dialog to print the word in reverse order. For example, if the user enters
the word "Java", your program should print.
avaJ
Hint: Use the charAt method and string concatenation. Begin with the empty string:
String reverse = "";
7. Write a program Rhyme.java that prints the following nursery rhyme in a message dialog. Spacing is
important!!
Jack and Jill p a hill
went u
To fetch a pail of water.
Jack fell d
o
w
n and broke his crown.
And Jill came t
u
m
b
l
i
n
g after
8. Write a Java application, NameGame.java , that reads in a single name from the user and then uses
that name to print the following verse. Two sample outputs are given. The portions of the verse that
depend on the user input are highlighted.
9. Write a Java application, Testing.java , that tests whether the following are legal Java expressions.
You should determine this by trying to print each of the following. Write up your answer by showing your
test code. And,include a written explanation of what is wrong with any of the illegal expressions. Explain
the result of any of the legal expressions.
a. toUpperCase("Java");
b. "Java".substring()
c. "I love ".concat("Java")
d. "Java".Length()
e. "Java".charAt(4)
f. "Java".charAt(1, 2)
10. In 3.6, we used the escape character '\n'. The additional escape characters, used for printing, are:
Write a Java application, Escape.java , that prints this sentence in a message dialog box
She said, "Hit the ON\OFF switch on Mike's computer."