Spring Semester 2005

Lecture Notes Three: Variables and types. Keyboard input.

# Types of Numbers (Numeric Types)

Last time we looked at two types of numbers:

• integers (such as `-5`, `23`, `10345` and so forth) and
• floating-point numbers (examples include: `5.7`, `12.0`, `-3.14`, etc.)

We will use `int` to denote the first category of numbers.

(Occasionally `long` will also be used and explained.)

We will use `double` as the label for the second category.

(Although `float` will also be used from time to time).

We use numbers to create expressions, which is a way of calculating other numbers.

The operators we looked at are:

• `-` (unary minus, as in `-5`)
• `+` (addition for numbers, concatenation for `String`s)
• `*` (multiplication)
• `/` (division)
• `%` (remainder)

If the two operands in an expression are both integers the result is also an integer.

If one of the two operands in an expression is a `double` the result will be a `double`.

So, some examples are:

• `1/2` evaluates to `0`
• `1.0/2` evaluates to `0.5`

# Precedence of Operators

Some operators have precedence over others:

• unary minus has the highest precedence (must be done first)
• multiplication and division (and remainder too) come next
• addition and subtraction have the lowest precedence

# Associativity

The order of the operations can be specified by parentheses.

In their absence operations of the same precedence are to be performed left to right.

Here are some examples:

• `1 + 2 - 3` evaluates to `0`
• `1 - 2 + 3` evaluates to `2`
• `1 / 2 * 3` evaluates to `0`
• `3 * 1 / 2` evaluates to `1`
• `1.0 / 2 * 3` evaluates to `1.5`
• `1 / 2 * 3.0` evaluates to `0`

This last one is (hopefully) clear.

Some more examples:

• `2 + 3 * 4` evaluates to `14`
• `2 * 3 + 4` evaluates to `10`
• `2 * (3 + 4)` evaluates to `14`

# `Math.sqrt(`...`)` and `Math.pow(`...`)`

• `Math.sqrt(x)` to calculate the square root of `x`
• `Math.pow(x, y)` to raise `x` to the power of `y`

What can we do with these expressions outside of printing their result?

We can store the number they evaluate to, for later use.

For that we use variables, which are:

names for locations that can keep values of a certain type.
The only types we know thus far are:

• `int` (for integers) and
• `double` (for floating-point numbers)

# Declaring Variables

Here's how you declare and initialize a variable of type `int`:
```int n; // declaration

n = 1; // initialization to 1```
`n = 1;` is an assignment statement:

• it has two parts separated by the equal sign
• on the left is the name of the variable whose value is being changed
• on the right there's an expression that must be of compatible type with the variable
• the expression is evaluated first, then the value is assigned to the variable
Here's how you declare and initialize a variable of type `int`:
```double m; // declaration

m = 1.0; // initialization to 1```
You will notice that in the last example
`m = 1;`
would have worked just as well.

`1` is compatible with `double` and `m` is now `1.0` as a matter of fact.

In the previous example

`n = 6 / 3; `
would have also been correct, but
`n = 6.0 / 3.0; `
would give an error. There's no room for the decimal part in `n` even if it's `0` (zero).

A variable should not be declared more than once.

A variable can changed its value any number of times.

# Compatible Types (Casting)

If types are compatible they can also be converted:
```m = 6;

n = (int)2.3 // n contains 2 now```
The last assignment uses casting.

In this case we drop the decimal part on purpose.

# Reading from the Keyboard (`ConsoleReader`)

The rest of this lecture will introduce `ConsoleReader`, which is a kind of `Penguin`.

```/*******************************************************
ConsoleReader class is used for keyboard input.
Just keep the source code of this class (the file)
in the same directory in which your other program
(the one that needs user input) resides.

In this particular case keep it in the same folder
with Conversion.java that has been presented above.
********************************************************/

import java.io.*; // I/O package needed

inStream));
}
String readLine() { // instance method
String inputLine = "";
try {
} catch (IOException e) {
System.out.println(e);
System.exit(1);
}
return inputLine;
}
int readInt() { // instance method
int n = Integer.parseInt(inputString);
return n;
}
double readDouble() { // instance method
double x = Double.parseDouble(inputString);
return x;
}
}```
You only need to know how to use it.

# A Complete Example

So we will discuss this program:
```/* A conversion program that illustrates how one can read input
from the keyboard using the textbook's ConsoleReader class */

class Conversion {
public static void main(String[] args) {
// now we can read from 'console'
System.out.println("Hi my name is Hal. What is your name?");
//// greet the user
//// wait for input and collect it (a String, for the name)
System.out.print("Hello, " + name + "! ");
//// echo the name to the user, raising user's confidence in us
System.out.println("How many dollars do you want to convert?");
System.out.println("(Please type an integer value, no decimal part)");
//// instruct the user what limitations you have (accepting only int's)
//// wait for the user to provide the sum to be converted
System.out.println("I see, you want to convert " + amount +
" dollars in British pounds. Very well...");
//// talk to the user, be friendly, echo information frequently
System.out.println("What is the conversion rate today?");
//// ask the user for the last piece of input
//// wait for the conversion rate, which can have a fractional part
System.out.println("Well, "+ name + " for " + amount + " dollars " +
"you can get: " + rate * amount + " pounds.");
//// do the calculation and report it to the user
System.out.println("Thank you for using Hal! Good-bye.");
//// thank the user for interest and say good-bye
}
}```

# Converting Strings into Numbers

The last thing we need to make clear is that strings of characters are different.

You can't say:

`int n = "12"; // won't work`
If you really want something like that you'd have to convert:
`int n = Integer.parseInt("12"); // now n is set to 12 `
If the conversion fails you will find out, the program will crash.

# A Review on Strings

Strings are indicated by characters grouped between double quotes.

You need a backslash in front of it (as in `\"`) to indicate a double quote inside a string.

(The backslash is an escape character. It disables the normal meaning of a double quote, as a delimiter.)

The backslash in front of a normal lowercase `n` indicates a newline.

(You wouldn't otherwise be able to write a newline in the string, since that would break the line.)

To indicate a backslash use the backslash in front of a backslash: `\\`.

So `"\"\\\n"` prints as a double quote followed by a backslash and a newline.

Strings could be concatenated using `+`.

Thus `"blue" + "berry"` evaluates to `"blueberry"`.

There will be a few more rules to keep in mind.

Last updated by Adrian German for A201/A597/I210 on `Tue Jan 18 14:56:06 EST 2005`