Introduction to Computer Science

Start Lecture #4

2.15: The String Type

In Java a String (note the capital S) is very different from a double, short, or char. Whereas all the latter are primitive types, String is actually a class and hence the String type is a reference type.

So what?

It actually is an important distinction, but not yet. Remember that Java was not designed as a teaching language but as a heavy-duty production language. Once consequence is that doing simple things (reading an integer, declaring a string) uses fairly sophisticated concepts.

Now we just want to learn how to declare String variables, write String constants, assign Strings and concatenate Strings. Fortunately, we can do all of these tasks without having to deal with the complications. Later we will learn much more about classes.

"This is A string"
"This is \u0041 string"

String s1, s2; s1 = "A string"; String s3 = "Another string"; s2 = s1 + " " + s3; s2 += " and more";
A string A string Another string and more Another string

The top line on the right shows a string.
The syntax is very simple: a double quote, some characters, a double quote. The second line is the same string.

Below the horizontal line are legal Java statements. The first declares two strings; they are currently uninitialized.
The second line assigns a string to the first variable The line declares a third string and initializes it.
The last two lines perform string concatenation

The last group of lines show the output when we println() each of the three strings.

2.16: Programming Style and Documentation

2.16.1: Appropriate Comments and Comment Styles

There are three types of Java comments.

  1. // comments the rest of the line
  2. /* ... */ comments the material ...
  3. /** ... */ uses javadoc

I will use only the first form, but you may use any of the three.

To learn about javadoc, see the reference in the book.

2.16.2: Naming Conventions

Java programmers tend to use the following conventions. I will try to adhere to them. I don't know if you can ask javac to tell you if you have violated the conventions.

2.16.3; Proper Indentation and Spacing

2.16.4: Block Styles

You should all be familiar with proper indenting to show the meaning of the program since Python requires it.

I use the end-of-line style but many prefer the next-line style. You may use either (see the book for examples of next-line style).

2.17: Programming Errors

I wish I could write a few words or pages (or books) that would show you how to avoid making errors and to find and fix error made by others. The best I can do, is to write programs in class. I will doubtless have errors and we can fix them together.

2.17.1: Syntax Errors

2.17.2: Runtime Errors

2.17.3: Logic Errors

2.1l.4: Debugging

Homework: 2.11 (copy of problem handed out in class for those w/o 8e).

2.18: (Gui) Getting Input from Input Dialogs

Chapter 3: Selections

3.1: Introduction

Essentially computer languages have a way to indicate that some statements are executed only if a certain condition holds.

Java syntax is basically the same as in C, which is OK but not great.

3.2: boolean Data Type

We have seen four integer types (byte, short, int, and long), two real types (float and double), and a character type (char). These 7 types are primitive.

We have also see one reference type (the String class). Note the capitalization, which reminds you that String is a class.

Java has one more primitive type (boolean), used to express truth and falsehood.
Comparison Operators
Operator  Name

==equal to
!=not equal to
<less than
<=less than or equal to
>greater than
>=greater than or equal to

Mathematicians, when discussing Boolean algebra, capitalize Boolean since it is named after a person, specifically the logician George Boole. Java of course does not capitalize boolean. Why?
Because boolean is a primitive type, not a class.

There are two boolean constants, true and false.

There are 6 comparison operators that are used to compare values in an ordered type (a type in which values are ordered). So we can compare ints with ints, doubles with doubles, and chars with chars. The result of a comparison is a boolean, namely true or false.

If values from different (ordered) types are being compared, one must be converted to the type of the other. Again this can be via coercion or type casting

int i = 1, j = 2;
boolean x, y = true, z;
x = i == j; // false
z = i < j; // true

On the right we see some simple uses of booleans. The one point to note is the distinction between = and == in Java.
The single = is the assignment operator that causes the value on the RHS to be placed into the variable on the LHS.
The double == is the comparison operator that evaluates its LHS and RHS, compares the results, and results in either true or false.

3.3: Problem: A Simple Math Learning Tool

No fun to use booleans before learning about if.

3.4: if Statements (a.k.a if-then Statements)

Found in basically all languages. We will see that the C/Java syntax for if permits the infamous dangling else problem.

3.4.1: One-Way if Statements

if (boolean expression) {
  one or more statements;
}

The simplest form of if statement is shown on the right.

if-then

The semantics (meaning) of a one-way if statement is simple and the same as in many languages.

3.5: Problem: Guessing Birthdays

Read

3.5 (Alternate): A Better Quadratic Equation Solver

Write a program to read in the coefficients A,B,C of a quadratic equation and print the answers. Handle the cases of positive, zero, and negative discriminant separately.

Let's do this in class. One solution is here.

3.6: Two-Way if Statements (a.k.a. if-then-else Statements)

if (boolean expression) {
  one or more statements;
} else {
  one or more statements;
}

Often if is used to choose between two actions, one when the Boolean expression is true and one when it is false.

The skeleton code for this if-then-else construct is shown on the right. The previous simpler skeleton is normally called an if-then even though Java and C do not actually employ a then keyword.

if-then-else

As the name suggests, the semantics of an if-then-else is to do the then or the else depending on the if. Specifically,

Omitting the {}

if (boolean expression)
   exactly one statement

if (boolean expression) exactly one statement else exactly one statement
if (boolean expression) { one or more statements } else exactly one statement

If any of the three blocks (the then block in the if-then statement, the then block in the if-then-else statement, or the else block in the if-then-else statement) consists of only one statement, its surrounding {} can be omitted.

Experienced Java programmers would almost always omit such {}, but it is probably better for beginners like us to leave them in so that all if-then's and all if-then-else's have the same structure. There is an exception, see below.

On the right we see three of the four possibilities.
What is the remaining possibility?
Ans: The then block has exactly one statement and no {} while the else block has one or more statements and does have the {}.

3.7: Nested if Statements

if (be1) { // be is Boolean expr
  if (be2) {
    ss1 // ss is statement(s)
  } else {
    ss2
} else {
  if (be3) {
    ss3
  } else {
    ss4
  }
}

The statement(s) in either the then block or the else block can include another if statement, in which case we say the two if statements are nested.

On the right we see three if statements, with the second and third nested inside the first.

If be1, the Boolean expression of the outside if statement evaluates to true, the second if statement is executed. If instead be1 is false, the third if statement executes.

There are eight possible truth values for the three Boolean expressions, but only four possible actions (ss1ss4).
Why?
Because for be1==true the value of be3 is irrelevant and for be1==false, the value of be2 is irrelevant.

Selecting One of Several Possibilities

if (be1) {
  ss1
} else {
  if (be2) {
    ss2
  } else {
    if (be3) {
      ss3
    } else {
      ss_default
    }
  }
}

Often deeply nested if-the-else's have the nesting only in the else part. This gives rise to code similar to that shown on the right.

Be sure you understand why this is not the same as separate (non-nested) if statements.

The trouble with the code shown is that it keeps moving to the right and, should there be many condition, you either get very wide lines or only have a few columns to use.

This is one situation where it pays to make use of the fact that the {} can be omitted when they enclose exactly one statement. To make use of this possibility, you must realize that an if statement, in its entirety, is only one statement. For example, the entire nested if structure we just saw is only one statement, even though it may have hundreds of statements inside its many {} blocks.

if (be1) {
  ss1
} else if (be2) {
  ss2
} else if (be3) {
  ss3
} else {
  ss_default
}

As a result we can remove the { and } from else { if ... } and convert the above to the code on the right.

Please read the code sequence carefully and understand why it is the same as the one above.

Note, in particular, that the indenting is somewhat misleading as the symmetric placement of ss1, ss2, s3, and ss_default suggests that they have equal status. In particular since be1==true implies that ss1 gets execute, you might think that be3==true implies that ss3 gets executed. But that is wrong! Be sure you understand why it is wrong (hint what if all the boolean expressions are true).

Indeed this pattern with all the statements in the then block is so common that some languages (but not Java) have a keyword elsif that is used in place of the else if above.

Other languages require an explicit ending to an if statement, most commonly end if. In that case no {} are ever needed for if statements.

Homework: 3.7 and 3.9. Handout for those w/o 8e.

3.8: Common Errors in Selection Statements

Don't forget the {} when you have more that one statement in the then block or else block. I recommend that, while you are learning Java, you use {} for each ss even if it is just one statement (except for the else if situation illustrated above).

Don't mistakenly put a ; after the boolean expression right before the then block.

Don't write if (be==true). Instead, write the equivalent if (be). Although the first form is not wrong; it is poor style.

The Notorious Dangling else

if (be1)
  if (be2)
    ss2
else
  ss1

The indenting on the right mistakenly suggests that should be1 evaluate to false, ss1 will be executed. That is WRONG. The else in the code sequence is part of the second (i.e., inner) if. Indeed, the Java (and C) rule is that an else pairs with the nearest unfinished if

In a language like Python that enforces proper indentation no such misleading information can occur.

if (be1) {   if (be1) {
  if (be2)     if (be2) {
    ss2          ss2
} else {       } else {
  ss1            ss1
}              }
             }

On the right, I have added {} to make the meaning clear. The code on the far right has the same semantics as the dangling else code above. There is no ambiguity: the outer then has not yet ended so the else must be part of the inner if.

The code on the near right has the semantics that the original indentation above mistakenly suggested. Again there is no ambiguity: The inner if has ended (it is part of the outer then block) so the else must be part of the outer if

3.9: Problem: An Improved Math Learning Tool

Read