Module 5: Conditional Statements
An example with integers
We will write an applet to customize a greeting based on age:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class AgeSpecificGreetingApplet extends Applet implements ActionListener {
// The string variable for the greeting.
String greeting;
// The text fields in which the user enter strings.
TextField nameField;
TextField ageField;
public void init ()
{
// -------------------------------------------------------------
// GUI stuff
setLayout (new BorderLayout());
Panel bottomPanel = new Panel ();
Label nameLabel = new Label ("Name: ");
bottomPanel.add (nameLabel);
nameField = new TextField (15);
bottomPanel.add (nameField);
Label ageLabel = new Label (" Age: ");
bottomPanel.add (ageLabel);
ageField = new TextField (2);
bottomPanel.add (ageField);
Button doneButton = new Button ("Press when done");
bottomPanel.add (doneButton);
doneButton.addActionListener (this);
add (bottomPanel, BorderLayout.SOUTH);
// -------------------------------------------------------------
// Initial value of greeting:
greeting = "";
}
// The method actionPerformed is called when the button is clicked.
public void actionPerformed (ActionEvent click)
{
// Retrieve the strings from the two text fields:
String name = nameField.getText ();
int age = new Integer (ageField.getText().trim()).intValue();
if (age < 2) {
greeting = "Coo coo, little baby " + name;
}
else if (age < 10) {
greeting = "Yo, kid, what's up?";
}
else if (age < 17) {
greeting = "Hi " + name + ", how's school these days?";
}
else {
greeting = "Good day " + name + "!";
}
// Redraw the applet:
repaint ();
}
public void paint (Graphics g)
{
// The Face, as before:
g.drawOval (40,40, 120,150); // Head
g.drawOval (57,75, 30,20); // Left eye
g.drawOval (110,75, 30,20); // Right eye
g.fillOval (68,81, 10,10); // pupil (left)
g.fillOval (121,81, 10,10); // pupil (right)
g.drawOval (85,100, 30,30); // Nose
g.fillArc (60,125,80,40, 180,180); // Mouth
g.drawOval (25,92, 15,30); // Left ear
g.drawOval (160,92, 15,30); // Right ear
// Draw the greeting:
g.drawString (greeting, 190,150);
}
}
Note:
- Notice the structure of an if statement:
if (some condition) {
some statements
}
else if (some other condition) {
some other statements
}
else {
yet other statements
}
- Both if and else are reserved words.
- You can have a single if all by itself, as in:
public void actionPerformed (ActionEvent click)
{
// Retrieve the strings from the two text fields:
String name = nameField.getText ();
int age = new Integer (ageField.getText().trim()).intValue();
if (age < 2) {
greeting = "Coo coo, little baby " + name;
}
// Redraw the applet:
repaint ();
}
- You can pair and else with an if part as in:
public void actionPerformed (ActionEvent click)
{
// Retrieve the strings from the two text fields:
String name = nameField.getText ();
int age = new Integer (ageField.getText().trim()).intValue();
if (age < 2) {
greeting = "Coo coo, little baby " + name;
}
else {
greeting = "Good day " + name + "!";
}
// Redraw the applet:
repaint ();
}
- Or, like in the example, you can have as many else if
parts in between as you like.
- The logic works like this:
- First the condition in the if clause is
evaluated. If true, the statement within executes and
then execution skips out to past the else clause.
- If the condition fails, the nearest else
clause is executed, which above is an else if
clause (else if (age < 10)).
- And so on.
- Thus, in the example, only one greeting assignment occurs.
- Link to applet
Let's consider some alternate ways of writing the same logic:
- Consider this way:
if (age < 2) {
greeting = "Coo coo, little baby " + name;
}
else if ( (age >= 2) && (age < 10) ) {
greeting = "Yo, kid, what's up?";
}
else if ( (age >= 10) && (age < 17) ) {
greeting = "Hi " + name + ", how's school these days?";
}
else if (age >= 17) {
greeting = "Good day " + name + "!";
}
- Here, each condition is more explicitly written.
- The result is the same because, for example,
the first else if clause will execute only
if age is at least 2.
- Notice the use of the && (AND) operator
to require both conditions to hold.
- Another way:
if (age < 2) {
greeting = "Coo coo, little baby " + name;
}
else {
if (age < 10) {
greeting = "Yo, kid, what's up?";
}
else {
if (age < 17) {
greeting = "Hi " + name + ", how's school these days?";
}
else {
greeting = "Good day " + name + "!";
}
}
}
- Yet another way:
if (age >= 17) {
greeting = "Good day " + name + "!";
}
else {
// Now we know age < 17
if (age >= 10) {
greeting = "Hi " + name + ", how's school these days?";
}
else {
// Now we know age < 10
if (age >= 2) {
greeting = "Yo, kid, what's up?";
}
else {
greeting = "Coo coo, little baby " + name;
}
}
}
In-Class Exercise:
Add a few more age ranges and responses to the applet above.
String comparisons
Consider this example in which two names are compared for
alphabetical order:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class AlphabeticalNamesApplet extends Applet implements ActionListener {
// Once they are alphabetically sorted, we'll place
// the names in these variables for use in paint()
String firstOne, secondOne;
// The text fields in which the user enter strings.
TextField nameField1, nameField2;
public void init ()
{
// -------------------------------------------------------------
// GUI stuff
Label nameLabel1 = new Label ("Name #1: ");
add (nameLabel1);
nameField1 = new TextField (10);
add (nameField1);
Label nameLabel2 = new Label ("Name #2: ");
add (nameLabel2);
nameField2 = new TextField (10);
add (nameField2);
Button doneButton = new Button ("Press when done");
add (doneButton);
doneButton.addActionListener (this);
// -------------------------------------------------------------
// Initial values of names: note the use of the reserved word "null"
firstOne = null;
secondOne = null;
}
// The method actionPerformed is called when the button is clicked.
public void actionPerformed (ActionEvent click)
{
// Retrieve the strings from the two text fields:
String name1 = nameField1.getText ();
String name2 = nameField2.getText ();
if (name1.compareTo (name2) < 0) {
// name1 comes alphabetically ahead.
firstOne = name1;
secondOne = name2;
}
else {
// name2 comes alphabetically ahead.
firstOne = name2;
secondOne = name1;
}
// Redraw the applet:
repaint ();
}
public void paint (Graphics g)
{
// If neither string has been set, don't do anything.
if ( (firstOne == null) || (secondOne == null) ) {
// Executing a "return" simply quits the method.
return;
}
// Now we know both strings are non-null, so draw the strings.
g.drawString ("In alphabetical order: ", 30, 120);
g.drawString (" " + firstOne, 30, 140);
g.drawString (" " + secondOne, 30, 160);
}
}
Note:
- Note the logic in the program:
- Variables name1 and name2 are used to
capture the strings from the text field.
- The method paint() simply paints the two strings
firstOne and secondOne as long as they are non-empty.
- Thus, once the button is clicked, it's up to
actionPerformed to set these variables correctly. This
is where we use a conditional statement.
- Object variables such as firstOne are initialized
to null (meaning "nothing").
- Notice how strings are compared:
if (name1.compareTo (name2) < 0) {
// ...
}
- The compareTo method of one string is given the
other string.
- It returns -1 if the first is alphabetically less.
- It returns 0 if they are the same.
- It returns 1 if the second is alphabetically less.
- Notice how in paint, we first check to see whether
variables firstOne and secondOne have values
assigned to them:
- The equality operator == is used to see whether
firstOne is set to null.
- Observe the use of the || (OR) operator:
the condition holds true if any of the two are null.
- Executing return (a Java reserved word) causes
a method to terminate immediately. Thus, once the return
is executed, nothing else in the method is executed.
- Link to applet
In-Class Exercise:
Add a third name to the above applet and display in correct alphabetical order.
For illustration, let's consider another way of writing the same program:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class AlphabeticalNamesApplet2 extends Applet implements ActionListener {
String name1, name2;
// The text fields in which the user enter strings.
TextField nameField1, nameField2;
public void init ()
{
// -------------------------------------------------------------
// GUI stuff
Label nameLabel1 = new Label ("Name #1: ");
add (nameLabel1);
nameField1 = new TextField (10);
add (nameField1);
Label nameLabel2 = new Label ("Name #2: ");
add (nameLabel2);
nameField2 = new TextField (10);
add (nameField2);
Button doneButton = new Button ("Press when done");
add (doneButton);
doneButton.addActionListener (this);
// -------------------------------------------------------------
// Initial values of names: note the use of the reserved word "null"
name1 = null;
name2 = null;
}
// The method actionPerformed is called when the button is clicked.
public void actionPerformed (ActionEvent click)
{
// Retrieve the strings from the two text fields:
name1 = nameField1.getText ();
name2 = nameField2.getText ();
// Redraw the applet:
repaint ();
}
public void paint (Graphics g)
{
// Print only if both strings are set.
if ( (name1 != null) && (name2 != null) ) {
g.drawString ("In alphabetical order: ", 30, 120);
if (name1.compareTo (name2) < 0) {
// name1 comes alphabetically ahead.
g.drawString (" " + name1, 30, 140);
g.drawString (" " + name2, 30, 160);
}
else {
// name2 comes alphabetically ahead.
g.drawString (" " + name2, 30, 140);
g.drawString (" " + name1, 30, 160);
}
}
// Nothing is needed in else clause
}
}
Note:
- Now we use only the name1 and name2 variables.
and perform the comparison directly in paint.
- The paint method has one large if block
that's executed only after the names have been entered.
- Notice the use of the != (NOT EQUALS) operator.
- Link to applet
In-Class Exercise:
Suppose we change the code in the above program so that the method
actionPerformed looks like this:
public void actionPerformed (ActionEvent click)
{
// Retrieve the strings from the two text fields:
String name1 = nameField1.getText ();
String name2 = nameField2.getText ();
// Redraw the applet:
repaint ();
}
What happens? Does it compile? Does it work? Explain.
In-Class Exercise:
Add a third name to the above applet and display in correct alphabetical order.
Add colors to improve the display.