Session 2 Lecture Notes for First Course in Java
course homepage      course calendar

2:
Thursday, June 7

This session covers the reading in Day 3: ABCs of Java, and Day 5: Lists, Logic, and Loops

Review of Session 1 and Short Quiz

Basics of (Java) Programming Language

  • Variables, Constants, and Data Types
    • boolean, char, int, double, float
    • arrays
    • constants are “final”
  • Declarations and Assignments
    • Data type + variable name
    • Equals (=)
  • Operators (arithmetic, logical, and binary)
  • Control and Flow Constructs
    • Conditional expressions (“if”, “else”)
    • Loops (“for”, “while”, “do … while”)
Three assignments:

[working code]

Homework Details

Homework Hints

Basics of (Java) Programming Language

Variables, Constants, and Data Types

A variable is a name for a piece of memory that stores a value. Each variable must have a name. 

Unlike JavaScript and Visual Basic, Java is a strongly typed programming language.

Number are represented in memory using bits, a bit is the smallest unit that a computer can work with. A bit has two possible values, 0 or 1.
Everything in a computer is represented using different numbers of bits.
A number is represented by a series of bits which represent different powers of 2.

An 8 bits number (byte):

Value of the number Bits
0 00000000
1 00000001 = 2^0
4 00000100 = 2^2+2^1+0^0
8 00001000 = 2^3+2^2+0^1+0^0
13 = 8 + 4 + 1 00001101 = 2^3+2^2+0^1+2^0
255 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 11111111 = ...
Type Size Range  Example
Integer types
byte 8 bits -128 to 127

-28 to (28-1)

Colors (RGB)
ASCII characters
short 16 bits -32,768 to 32,767

-216 to (216-1)

Unicode (world languages)
int 32 bits -232 to (232-1) counters in loops
long 64 bits -264 to (264-1) big numbers
Floating point types
float 32 bits   floating point (currency, temperature, length)
double 64 bits   floating point (large numbers, such as for astronomy or subatomic physics)
Special types
boolean   true
false
logic test with if
char 16 bits unicode characters alphabets and numerals

Note: Java does not have explicit pointers. Instead, a variable references an object. When you make a change, you change the original object. However, when you work with a primitive data type, such as an integer, you are working directly with values.

Constant

A constant variable is a variable which is assigned a value once and cannot be changed afterward (during execution of the program). The compiler optimizes a constant for memory storage and performance.

Examples of constants

Array

An array stores multiple variables of 

Examples of arrays

Statements

A statement is a sentence.

Every statement must end with a semicolon (;).

Declarations and Assignments

A declaration is a statement that lets the compiler know that we are going to use a variable to refer to a value of a certain type.

An assignment gives (assigns) a value to a variable. Typically, in Java, we assign a value to a variable when we declare that variable.

For example,

int temperature = 70; // Fahrenheit
float drunk = .01; // in percent
final int BOILING_POINT = 212; // a constant
// What follows is an array of characters 
// for the 7 days of the week.
// (Single quotes are for chars.)
// Each element has a unique index. 
// The first 's' (Sunday) has the index of zero.
// The second 's' (Saturday) has the index of 6.

char[] daysOfTheWeek = {'s', 'm', 't', 'w', 't', 'f', 's'};
// Use double quotes for strings.
String[] myDays = {"Sunday", "Monday", "Tuesday"};

Conventions

varName;  // not capitalized initially, but each subsequent word in the name is capitalized

methodName(); // not capitalized initially, but each subsequent word in the name is capitalized

CONST_NAME // all capital letters with underscore to separate words in the name

ClassName // initial capital letter and capital letter for each word in the name

 

Data type + variable name

The syntax to declare a variable is to specify the type, then specify the name of the variable.

You can also assign a value to the variable when you declare it.

<type> <name> [= <value>];

// brackets mean optional

The syntax to assign a value to a variable is to put the name of the variable, followed by an equal sign (=) and the new value. The equal sign is the assignment operator.

<name> = <value>;

Operators 

arithmetic

result = <operand1> <operator> <operand2>;
example: myLongString = myShortString + myOtherString;

logical

Logical operators test a condition and return a boolean value (true or false).

Truth table

Operand1 Operand2 == != && ||
true true true false true true
true  false false true false true
false true false true false true
false false true false false false

binary

Computers represent numbers internally as a certain number of bits. The binary operators operate on the bit level.

The truth table would be similar to the one above, but instead of comparing the whole operands, we compare each bit of the operands. 

Operand1  & Operand2 result
0 0 0
1 0
1 1 1
Operand1  | Operand2 result
0 0 0
1 1
1 1 1

We can also shift a series of bits. Reasons to shift bits is to manipulate an image (image processing) or for optimized "calculation", you can multiply by two by shifting the bits to the left by one bit and vice versa. 

Note: A shift left by n is the equivalent to multiplying two to the power of n, and this is the most efficient way to multiply. For example, shifting left one digit multiplies by two.

Control and Flow Constructs

A programming language is more flexible than a hand-held calculator because a computer can perform conditional logic. In other words, you can write decision-type statements.

Conditional expressions (“if”, “else”)

A conditional block is a group of statements executed only if a certain condition is met. A conditional block is preceded by a conditional expression ("if (<condition>)") and is surrounded by curly braces. An if block can be optionally followed  by an else block.

Syntax:

if (<logical expression>)
{
    statement;
}
[ else {statement;} ]

Example:

if (gotPayRaise)
{
    //	the following lines (between the braces) get executed
    //  if and only if the boolean expression 'gotPayRaise'
    //	evaluates to true. 
    buy("Red Ferrari");
    //	here is a nested if block
    if (anyMoneyLeft)
    {
            buy("gas");
    }
    else  //   followed by an else block
    {
	//  this block I executed if the boolean expression
	//  'anyMoneyLeft' evaluates to false. 
        askMomFor("gas money");
    }
} 

Loops (“for”, “while”)

Computers are extremely fast and reliable for performing an operation repeatedly. Loops are programming constructs which enable you to executes a code block more than once. Batch processing, such as a phone company billing thousands of users, is an area where looping is appropriate.

A while loop is good when you do not know the number of times to repeat the loop.

while (anyMoneyLeft)
{
    registerFor("another class at UC Berkeley Extension");
}

For example, you might use a while loop to wait for a mouse click from the user.

A for loop is good when you know the number of times to repeat the loop. For example, a phone company knows how many telephone accounts it has issued.

for (initialization; test; increment)  // any variable you declare here has its scope limited to this block
{
      statement;
}

for (int customerIndex = 0; customerIndex < totalNumberOfCustomer; customerIndex++)
{
    billCustomer(customerArray[customerIndex]);
}

We can rewrite this for loop as a while loop:

{ // some code 
    int customerIndex = 0;
    while (customerIndex < totalNumberOfCustomers)
   {
        billCustomer(customerArray[customerIndex]);
        customerIndex++;
    }
}

Note: There can be a slight difference in the total number of executions.

Do while loop

     // Unlike a while loop, the do while is guaranteed to always runs at least once

Break statement

...

Switch statement

The switch statement enables you to avoid complex sequences of else if statements.

if (v = = 1)
  // do something
else if (v = = 2)
  // do something different
else if (v = = 3)
  // do a different something different

Here's how it looks:

switch (v)
{
    case 1:
       // do something
       break;
    case 2:
       // do something different
       break;
    case 3:
       // do a different something different
       break;

   default:
}

Homework Details:

(1)
Write a Unit Conversion Utility Class
We use the conversion constants at
http://www.onlineconversion.com/length.htm

This exercise gives you an opportunity to work with several of the operators in Java.
Note: you don't need object-oriented design to make this conversion utility work.

Convert a metric integer value for a unit of distance into a U.S. units of distance. 
We only care about precision to the inch.
Your algorithm will divide by the largest unit first, and then divide by the next largest unit. 

Note: Although the input value is an integer, you will do arithmetic operations with the floating point type, double. This requires casting from an int to a double. Here is the syntax: 
    // Cast the double variable, myDouble, 
    // into an int variable, myInt.     
    myInt = (int) myDouble

EXAMPLE
170,000 centimeters converts to:
1 mile + 99 yards + 0 feet + 5 inches

You can either hardcode a number of centimeters into a variable, or read in from the console reader.

Homework Hints

This applet demonstrates the complete functionality, and even includes an extra feature: user interactivity:
http://www.wordesign.com/java/conversionappletclasses_docs/classes/ConversionApplet.html

Here is the javadoc:
http://www.wordesign.com/java/conversionappletclasses_docs/docs/

(2)
Factorial exercise: Write a Java application that computes the final product by using a while loop.
You should show the output of your program with the following values: 0, 1, 5, 7.

For example, 

5! = 5 x 4 x 3 x 2 x 1 = 120
4! = 4 x 3 x 2 x 1 = 24
3! = 3 x 2 x 1 = 6
1! = 1
Note this special case:  0! = 1
The general formula for your algorithm is: n! = n(n-1)!
For your output, you can do either of the following:

_________________________
course homepage      course calendar