[go: up one dir, main page]

0% found this document useful (0 votes)
13 views20 pages

Lab 03

This document provides instructions for a lab on object-oriented programming in Java. It discusses using pre-defined classes like JFrame and JOptionPane, and the String class. It walks through creating a basic Java application, including writing, compiling, and running a program. It also covers Java naming rules and conventions.

Uploaded by

Nedal Muhammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views20 pages

Lab 03

This document provides instructions for a lab on object-oriented programming in Java. It discusses using pre-defined classes like JFrame and JOptionPane, and the String class. It walks through creating a basic Java application, including writing, compiling, and running a program. It also covers Java naming rules and conventions.

Uploaded by

Nedal Muhammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

J A V A L A B M A N U A L

LAB OBJECT ORIENTED PROGRAMMING IN JAVA

3 Working With Pre – Defined Classes


JFrame, JOptionPane and String
TABLE OF CONTENTS:
3.1 Java Naming Rules and guidelines
3.2 Using a JFrame object
3.3 Using JOptionPane to Print a Message
3.4 Reading Error Messages
3.5 Combining Statements and the Newline Character
3.6 Using JOptionPane to Input a String
3.7 String Methods
3.8 Programming Exercises

PURPOSE

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
 Read: Read Chapters
 create a directory called lab3 in which you should save all the files completed as part of this lab.

TO COMPLETE

 This is an individual lab. You may get help from other students as well as the lab tutor.
 Hand in a copy of your completed programs to the lab tutor.

3.1 WRITING A FIRST JAVA APPLICATION


U S I N G I D E T O E D I T, C O M P I L E A N D R U N A J AVA P R O G R A M

This portion of the lab will take you through the step – by – step process for editing, compiling, and running your first Java
application.

S t e p 1 : Understand what problem the program is supposed to solve.


P r o b l e m : Write a program that adds five onto a value stored in memory.

S t e p 2 : Hand write the program.


Once you understand what a program is supposed to do, you should write the program using pencil and paper.
This should always be done before you begin to enter the code in a text editor.
//First Java Program by Tom Jones
class First

PAGE 3.1
{
public static void main(String[] args)
{
int number;
number = 31;
number = number + 5;
}
}

A brief explanation of the Java code above:


//First Java Program by Tom Jones The two forward slashes define line comment.
Comments are not part of the program but are for the benefit of the reader.
You should replace the name Tom Jones with your name.
class First - All Java code must be inside of a class. We begin with the Java reserved word class and then
choose an appropriate name for the class. I have chosen First. The class is defined between a set of matching
braces, {} , which define the beginning and end of the class. We say the braces delimit , define the beginning and
end of the class. The braces are called delimiters .
public static void main(String[ ] args) is the header of the main method and must appear in all Java
applications. A method contains a set of statements that are executed by the computer when the program is run.
Again, the body of a method is delimited by a set of matching braces.
int number; is a variable declaration statement . Such a statement reserves memory that can be
accessed with the name number instead of using the actual memory address, as is necessary with machine
language. In addition, this memory location will store an int , a four – byte integer value. It is the responsibility
of the computer to keep a table of all variables used in a program along with information about each variable that
includes the memory address associated with the variable and the type of data that is stored in this memory
location.
number = 31; assigns 31 (a decimal value) to the memory location that has the name number .
number = number + 5; assigns number + 5 to number . Once the memory location number is
overwritten with 36, the original value, 31, is lost.
A program statement ends with a semicolon. You should notice that the body of the main method contains
three statements that declare the variable number , assign an initial value to number, and then calculate and
assign a new value to number .

S t e p 3 : Edit (Enter and save) the program.


Use a text editor to implement the program. Open IDE . You should have an empty document that you will use to type the
program. If you do not have a blank document, then either click on the New Document icon or go to File – New .
Type in the program.
When done save the file in the MyDocuments folder of the PC with a .java extension, as follows:

o click on File – Save As.


o When the Save As window opens
o if necessary, navigate to the MyDoucments folder.
o look at the bottom portion of the window for the Save as type: textfield. If Java(*.java) does not
appear in the textfield click on the menu arrow and choose Java(*.java) .
o type First into the File name: textfield since the name of the file should match the name of the class.
o click the Save button.
S t e p 4 : Compile the program
To compile the source file into a bytecode file, click on Tools – Compile Java.

PAGE 3.2
J A V A L A B M A N U A L

For a program to compile, it must follow all the rules of Java syntax. If your file contains any kind of syntax error, such as
a missing semi-colon or quote, the program will not compile.
How can you tell if the program did or did not compile?
 If it does not compile, you will see one or more error messages in Textpad. Error messages can be very
informative. But, since this is a first program, any error message may be difficult for you to read. You must go
back to Step 2 and edit the existing file to remove any syntax errors and then recompile the code. Except for
spacing, you must follow the sample code exactly.
 If the file does compile , you will hear a sound and your file First.java will be displayed. The result of the
compilation process is the creation of a new file called First.class that contains the Java bytecode version of
the program. If you would like to see the listing of this file, again go to Files – Open and choose Files of
Type: All Files (*.*) and you should see the name of the bytecode file.

S t e p 5 : Run the program

Click on Tools – Run Java Application


Record the results.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________

S t e p 6 : Maintain the program


At this point, you can make changes to your program by going back to Step 2 followed by Steps 3 & 4. Modify your
program by adding the highlighted lines.
//First Java Program by Tom Jones
class First
{
public static void main(String[] args)
{
int number;
number = 31;
System.out.println(number);
number = number + 5;
System.out.println(number);
}
}

System.out.println(number) ; prints the value stored in the memory location number to the
monitor. System.out is the monitor. println is a message to print a new line. What is printed in this
new line is determined by what is placed between the pair of parentheses. In this case, the variable
number is passed, so the value stored in number is printed twice, after number is initialized to 31
and after 5 is added onto the value stored in number .
Compile and run the modified program. Record the results.

_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________

LAB 03 IS ALMOST COMPLETE


1. Always do a cleanup of My Documents
o Save any .java files in the lab03 directory on your memory device.

PAGE 3.3
o Remove the .java and .class files from MyDocuments.
 highlight the .java and .class files that you created and delete them by choosing File –
Delete or click on the big red X on the menu bar.

3.2 Java Naming Rules and guidelines


An identifier is a word that is used to name a class, method, variable, or constant.
Java has rules for choosing a legal identifier. Recall that Java is case sensitive.

Java Rules for Choosing Identifiers


1. An identifier may use all letters, a – z and A – Z, all digits, 0 – 9, the underscore _ and $ .
2. An identifier may not begin with a digit or $.
3. An identifier may not be a Java reserved or key word , which is a word that has a special meaning in Java. This is
a list of Java reserved words, with words that we have already used highlighted.

abstact boolean break byte case catch


char class const continue default do
double else extends final finally, float
for goto if implements import instanceof
int interface long native new package
private protected public return short static
strictfp super switch synchronized this throw
throws transient try void volatile while

Java Naming Guidelines


In addition to the naming rules, there are also guidelines, or conventions, that were established by the authors of the Java
API. If a guideline is not respect, the code will compile, but it will be more difficult to read. Knowing and using these
guidelines will help you understand code that uses Java API classes. Choosing identifiers that indicate the purpose of the
class, method or data value also makes code understandable and is known as self – documentation .
C l a s s N a m e s : should 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 : should 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 : should 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 : should be completely capitalized, additional words are separated with an underscore
character _ . Examples: PI, MAX_VALUE, INTEREST_RATE

You are always expected to follow the Java guidelines for choosing identifiers.

PAGE 3.4
J A V A L A B M A N U A L

3.2 USING A JFRAME OBJECT


Java provides us with a library of classes called the Java Application Programming Interface, or Java API. In this session,
we will use the predefined classes JFrame, JOptionPane, and String .
You will learn to define your own classes in a later session.
Java is an object-oriented programming language. Before an object can exist, a class must define what characteristics and
behaviors an object will have.
The class is not the same as the object. Rather, the class is a template from which objects can be created.
A class is a template that describes the characteristics and behaviors that objects of this type will have.
The characteristics are data values, and the behaviors are methods.
An object is an instance of a class.
Experiment 1: HelloWorld.java title

Traditionally, a programmer writes a Hello World program as his


first program in a new programming language. For you, this will be
your second program. Instead of printing to System.out , as done

height in pixels
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

JDialog object width measured in pixels

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 IDE 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 lab03 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 be found more easily.

Declaring and Creating an Object


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. Before an object can be used, it must be declared and created.
The declaration statement :
JFrame frame;
allocates memory known as frame that can refer to a JFrame object.

PAGE 3.5
To create , or instantiate , an object, use the new operator and the name of the class. The object creation – assignment
statement

frame = new JFrame(); frame JFrame

is read right to left, "create a new JFrame object and assign it to frame ".
To the right is a state of memory diagram illustrating what is stored in
memory after the two statements is executed.
Step 2: Add the two new statements to the main method of your program. The comments are not part of the code and do
not need to be included when you enter the new code.

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

________________________________________________________________________________________________
________________________________________________________________________________________________

Using Instance Methods


JFrame
A JFrame object has characteristics that include its height, frame width
width, and title . Values can be assigned to these instance variables height
by sending appropriate messages to the object. title

To send a message to an object, a method is invoked on the object. A method that is invoked on an object is an instance
method . To invoke an instance method, follow the name of the object with a dot ( . ) followed by the name of the method,
which is always followed by a pair of parentheses.
objectName.methodName()
Information that is passed to a method is called an argument . Arguments are separated by commas and placed between
the parentheses.

PAGE 3.6
J A V A L A B M A N U A L

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, measured in the number of pixels,
of the JFrame .
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.

________________________________________________________________________________________________
________________________________________________________________________________________________

S t e p 5 : 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 . 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 : To close this program, click on the X in the upper right – hand corner of all windows that were opened when the
application was run.
S t e p 6 : Experiment by changing the integer arguments in the statement that sets the size 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 your answer indicate how you made this determination.

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

3.3 USING JOPTIONPANE TO PRINT A MESSAGE


A JDialog object is used to communicate with the user. it is used to print a message. When the OK button is clicked, or
the Enter key is pressed, the dialog box closes. The JDialog also has characteristics such as width , and height that need
to be set to dimensions that accommodate long or multiple lines of output. Later we will use a JDialog for user input.

Using Class Methods


Rather than create a JDialog object directly, the javax.swing.JOptionPane class defines class methods that create
JDialog boxes with appropriate dimensions, title, and components, such as buttons.
A class method is invoked on the name of the class in which it is defined rather than on an object.

PAGE 3.7
The JOptionPane class method showMessageDialog() is used to display a message in a dialog box.

JOptionPane.showMessageDialog(frame, "Hello World");


There are two arguments that must be passed to the method:
 frame identifies the parent component on which the dialog box is centered.
 "Hello World" 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 expect?

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

3.4 READING ERROR MESSAGES


Learning to read error messages is an important skill that you should develop as the semester continues. As your programs
become larger, the number of error messages will increase. During the semester, you will learn how to control the number
of error messages by implementing code in small, logical sections.

Instructions for Recording Error Messages


In this lab, you will work with controlled errors. That is, the file will contain only one intentional error at a time. For each
error you should:
1. Introduce the single error into your code.
2. Save the file that now contains the error.
3. Compile the program.
4. If there is a compiler error, record "the essence" of the error message and the line number on which it was detected. If
the program compiles, run it.
5. Correct the error.
To begin, be sure that your program HelloWorld.java compiles and runs.

PAGE 3.8
J A V A L A B M A N U A L

Syntax Errors
A syntax error occurs when the rules of the language are violated. These errors are always found by the compiler. The
actual 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 .

File name line # the error.

C:\Documentsand Settings\Marian Manyo\My Documents\cosc060\HelloWorld.java:11: ')' expected.


frame.setTitle(My Hello World Program");  the line of code where error was detected.
^  character where error was detected

C:\Documentsand Settings\Marian Manyo\My Documents\cosc60\HelloWorld.java:11: unclosed string literal


frame.setTitle(My Hello World Program");  the line of code
^  character where error was detected
2 errors

Now compile your code. Record the "essence" of the error messages, e.g. " ')' expected " and
" Unclosed string literal "

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

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.

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

PAGE 3.9
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 the 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();

PAGE 3.10
J A V A L A B M A N U A L

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.

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.

________________________________________________________________________________________________
________________________________________________________________________________________________

3.5 COMBINING STATEMENTS AND THE NEWLINE CHARACTER


Step 8: Make three additional changes to the current program.

Using the wildcard, *


When one or more classes are imported from a specified package, it is often easier to import all classes from the specified
package. To do this, use the wildcard symbol, *, to represent all class files in the package. This does not reduce the
performance of a program. Remove the statements
import javax.swing.JFrame;
import javax.swing.JOptionPane;

and replace them with the single statement


import javax.swing.*;

Combining declaration and initialization statements


The declaration and object creation statements can be combined into a single statement.
Remove the statements
JFrame frame;
frame = new JFrame();

and replace them with the single statement


JFrame frame = new JFrame();
that both declares a JFrame variable frame and initializes it to refer to a new JFame object.

PAGE 3.11
Using the newline character '\n'
Special characters, such as the newline character, can be printed using a sequence of two characters, the escape character,
'\' , followed by another character whose normal meaning "is escaped". The combination of the characters '\' and 'n'
represents the newline character '\n' , which returns the printer carriage to the beginning of the next line.
Modify the message that is displayed in the JDialog message box.
JOptionPane.showMessageDialog(frame, "Hello\nWorld!");
The entire program should now be.
import javax.swing.*;
class HelloWorld
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(500,400);
frame.setTitle("My Hello World Program");
frame.setVisible(true);
JOptionPane.showMessageDialog(frame, "Hello\nWorld!");
}
}

Compile the revised code and run the program. Record the results.

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

Step 9: Make changes to the statement.


JOptionPane.showMessageDialog(frame, "Hello\nWorld!");
So that it prints the message in a column:
H
e
l Record your change to the statement.
l
o _________________________________________________________________________

W _________________________________________________________________________
o
r
l
d
!
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.

PAGE 3.12
J A V A L A B M A N U A L

3.6 USING JOPTIONPANE TO INPUT A STRING


The JOptionPane class method showInputDialog is used to read user input. The expression
JOptionPane.showInputDialog(frame, "Enter your name")

causes an input JDialog , centered on frame , to appear. The method's


String argument is the prompt. The user may type a single string of
any number of characters in the text field. When the OK button is
clicked, the input dialog is closed, and the method returns the entered
String . In order to use the String that is returned by the
showInputDialog method, it must be assigned to a String variable.
The statement

String name = JOptionPane.showInputDialog(


frame, "Enter your name");
declares a String variable name and assigns to it the String returned by the showInputDialog() method. Due to the
length of the line of code, it has been broken into two lines by using the <Enter> key at an appropriate place. Long lines
should always be broken into multiple lines rather than using the word – wrap feature of a text editor. Lines, including
leading spaces, should never be longer than 80 characters.
The operator + can be used to concatenate, or add, two String objects to form a new String object. Therefore, if name
refers to the String "Mable" , the expression.
String sentence = "My name is " + name
creates the new String "My name is Mable" and assigns it to the String variable sentence .

name String String


sentence
"Mable" "My name is Mable."

The statement
JOptionPane.showMessageDialog(frame, "My name is " + name);
creates the same string for printing without storing it to sentence .
S t e p 1 0 : Edit your modified HelloWorld.java as follows:
 Before any message is printed, prompt the user for his/her name.
 After the Hello World message is printed, use a second message dialog to print the user's name.
Compile and run the program. After entering your name in the input dialog box, click the OK button. Record the results.

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

Run the program a second time. This time click the Cancel button instead. Record the results.

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

PAGE 3.13
3.7 STRING METHODS
The Java API java.lang.String class defines methods that can be invoked on String objects. We will experiment with
only a small number of these methods.
E x p e r i m e n t 2 StringTest.java
Step 1: To experiment with these methods, create a new program file called StringTest.java similar to
HelloWorld.java . Declare the class and the main method. Inside the main method, create a J Frame frame object, and
using an input dialog box, prompt the user for a word, saving the input in the variable String word .
Compile the code and run the program to be sure it runs as expected. 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 and a name followed by a set of parentheses surrounding an optional list of variables called parameters. The
parameter list tells the user the number and types of arguments that must be passed to the method when it is called ( or
invoked ). We will look at these String methods with headers:

return type method Name (<optional parameter list>)


String toUpperCase ()
int length ()
int indexOf (String s)
char charAt (int index)
String substring (int beginIndex, int endIndex)
String substring (int beginIndex)
In the explanations of the methods that follow, the reserved word this refers to the object on which the method is invoked.
Therefore, in the statement
word.toUpperCase();
word is this object.
String toUpperCase(): creates and returns a new String whose letters are the upper-case equivalents of the
letters in this String . 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

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

String
Invoking the method toUpperCase() on a String word
"Java"
does not change the existing String , rather, it creates a
new String . Therefore, word remains unchanged.
String
"JAVA"

Step 3: To change word to its upper-case equivalent, the returned String needs to be assigned to word or to some other
String variable.
Replace the statement X String
word
"Java"

PAGE 3.14
J A V A L A B M A N U A L

word.toUpperCase();
with the statement
word = word.toUpperCase(); String
that assigns the returned String to word . "JAVA"

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.

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

int length (): returns the number of characters in this String .


S t e p 5 : Without removing any statements, add to the end of main the statement.
JOptionPane.showMessageDialog(frame, word + " has length " + word.length());
Predict what will be printed in the two message dialog boxes if you enter your full name.

________________________________________________________________________________________________
________________________________________________________________________________________________
Compile and run the revised program, entering your full name. Record the two printed messages.

________________________________________________________________________________________________
________________________________________________________________________________________________

PAGE 3.15
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): returns an integer representing the index of the first occurrence of the argument s in
this String.
M a r q u e t t e
0 1 2 3 4 5 6 7 8

If the entered word is "Marquette"; the method call.


word.indexOf("q")
returns 3 because the string "q" is found beginning at index 3.
S t e p 6 : Without removing any statements from main, add the statement
JOptionPane.showMessageDialog(frame,
word + "\n" +
"Index of e is " + word.indexOf("e") + "\n" +
"index of tt is " + word.indexOf("tt") + "\n" +
"index of Mar is " + word.indexOf("Mar") + "\n" +
"index of m is " + word.indexOf("m"));
as the last statement in main . Predict the output of the last message dialog box if "Marquette" is entered.

index of e is _____________________
index of tt is _____________________
index of Mar is ___________________
index of m is _____________________
Compile and run the revised program, entering "Marquette" . Correct your predictions if necessary.
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 7 : Without removing any statements, add the statement
JOptionPane.showMessageDialog(frame,
word + "\n" +
"Char at index 1 is " + word.charAt(1) + "\n" +
"Char at index 3 is " + word.charAt(3) + "\n" +
"Char at index 8 is " + word.charAt(8));

as the last statement in main . Predict the output in the last message dialog box if "Marquette" is entered. Then
compile and run the revised program and correct your predictions if necessary.
char at index 1 is _____________________
char at index 3 is _____________________
char at index 8 is _____________________
Run the program one more time. This time enter "Warriors" when prompted for a word. The program will have a
runtime error, causing an Exception to be thrown and the program to end. If you close the StringTest windows, you will
see the Exception printed on the black System command window.
Record the essence of the error and explain why the error occurred.

________________________________________________________________________________________________
________________________________________________________________________________________________

PAGE 3.16
J A V A L A B M A N U A L

________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________

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

For example, if word is "Marquette" then the expression.


word.substring(3,6)
returns "que" , which is the substring from the character at index 3 up to, but not including, the character at index 6.
However, the expression
word.substring(3)
returns "quette" , which is the substring from the character at index 3 to the end of the string.
Step 8: Without removing any statements, add the statement.
JOptionPane.showMessageDialog(frame,
word + "\n" +
"Substring from 1 to 5 is " + word.substring(1,5) + "\n" +
"Substring from 1 is " + word.substring(1) + "\n" +
"Substring from 4 to 8 is " + word.substring(4,8) + "\n" +
"Substring from 4 is " + word.substring(4) + "\n" +
"Substring from 0 to 1 is " + word.substring(0,1) + "\n" +
"Substring from 0 to length is " +
word.substring(0,word.length()));

as the last statement in main . Predict the output of the last message dialog if the entered string is "Marquette" .
Then, compile and run the revised program and correct your predictions if necessary.

substring from 1 to 5 is ____________________________


substring from 1 is ____________________________
substring from 4 to 8 is ____________________________
substring from 4 is ____________________________
substring from 0 to 1 is ____________________________
substring from 0 to length is ________________________

PAGE 3.17
Overloaded methods are at least two methods in the same class that have the same name.
Answer this question: How does the computer know which of the two substring methods to execute?

________________________________________________________________________________________________
________________________________________________________________________________________________

S t e p 9 : Add a comment to this file that contains your name and the purpose of the program.
Here are three samples, the first two use a block comment and the third uses multiple inline comments.

/* Author: Stu Dent


Class: COSC060 – Section 1001
Purpose: Investigate different String methods
*/

/***************************************************
* Author: Stu Dent
* Class: COSC060 – Section 1001
* Purpose: Investigate different String methods
***************************************************/

// Author: Stu Dent


// Class: COSC060 – Section 1001
// Purpose: Investigate different String methods

 Print a copy of HelloWorld.java and StringTest.java to hand in to the lab tutor.


To save paper, within IDE copy each of these programs into a single file lab03.txt and then print lab03.txt.

 Be sure that the final versions of these two programs are stored on your memory device in the lab03 directory.

PAGE 3.18
J A V A L A B M A N U A L

3.8 POST LAB PROGRAMMING EXERCISES


1. Write a program MadLib.java that prompts the user for words that are either parts of speech or specific types of
words, such as noun, verb, adjective, animal, number etc.. The entered words are then printed as part of one or more
sentences. For example: Prompt the user, using four separate input dialogs, for an animal, plural noun, number and
adjective. If the user enters, respectively, "elephant", "books", "13", and "beautiful", then the program prints, using a
message dialog: "My pet ELEPHANT likes to eat BOOKS. He eats 13 times a day and is beginning to look quite
BEAUTIFUL." The user-entered words should be capitalized when printed.
Make up your own MadLib that uses at least four user-entered strings.

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 Middle Initial.
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 Tones" would be printed in a message dialog.

6. 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.

7. 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 "" and concatenate characters onto it.

PAGE 3.19
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:

\" is used to print a double quote

\' is used to print a single quote

\t is used to print a tab

\\ is used to print a backslash

\r is used to print a return, which returns the carriage to the beginning of the same line

\n is used to print a newline, which returns the carriage to the beginning of the next line

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."

PAGE 3.20

You might also like