Session 2  Lecture Notes for First Course in Java

An Overview of Java

This lecture covers  Chapter 1: Java Fundamentals, Chapter 2: Introducing Data Types and Operators, and Chapter 3: Program Control Statements

 

(syllabus and calendar)

Review of last week

Method call and other demo programs

Statements and expressions

Declarations and assignments

Sample programs

Control statements

  • if
  • for

Code blocks

Language tokens

Built-in methods (libraries)


Data Types

Break

 our comments from the class:  commented.zip 

 zip of examples before class without latest comments

Homework


Method Call

We will explore method more later in the course. This is just a preview.

Character Arithmetic

If Statement

Block Scope

Initialization of a Variable

Variable Scope

Modulus and Truncation

Relational and Logical Operators

Short-circuit Operators

 

Automatic Conversion of Long to Double

Explicit Casting Syntax

Truth Table

Promotion

Cast Usage


Statements and Expressions

What is the difference between a comment, a statement, and an expression?

Statements

A statement is a command that you write in your program.
Syntax: a statement must end with a semicolon (;) so that the parser in the Java compiler (javac) knows this is the end of your statement.

System.out.println("Hello Luke"); // pass a string argument to a method
double bodyTemperature = 98.6; // assign a value to a primitive variable
HumanBeing.inalienableRight = pursuitOfHappiness; // assign a value to a property of an object

Comments

Comments are for human code readers. The compiler ignores comments.
Insert comments in your code so that you, and others who will use your code, know what the code is about.
Good comments make code more maintainable, even for the original programmer.
It is more common for code to have too few comments than too many comments.

In the preceding statements, a comment follows each statement. 
Two slash characters (//) define the comment through the end of the current line.

/* A slash followed by an asterisk
defined the beginning of a multi-line comment,
which ends with the reverse, an asterisk, followed by a slash */ 

Expressions

An expression is a statement that returns a value. 
In both examples below, the Java virtual machine will:

  1. Perform a calculation or an evaluation.
  2. Return a return value.
sum = priceOfItem1 + priceOfItem2; // the return value is stored in the variable sum
selfEvidentTruth = HumanBeing.IsCreatedEqual();  // boolean return value must be true or false

Declarations and Assignments

What is the difference between a declaration and an assignment?

A variable is a named location in memory. 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. Syntax requires that we declare the type before we declare the variable's name.

Declarations without assignments

int temperature;
float drunk;
final int BOILING_POINT;
char[] daysOfTheWeek;
String[] myDays;

Declarations followed by assignments

The declaration statement can be separate from the assignment statement.
The assignment operator is  =
The operand to the left of the assignment operator is assigned (or gets) the value of the operand to the right of the assignment operator.

int temperature;
temperature = 100; // the temperature variable "gets" the value of 100
double temperature;
temperature = 100.0001;

Declarations and assignments

An assignment gives (assigns) a value to a variable. Typically, in Java, we assign a value to a variable when we declare that variable.
However, we can assign a value later. And, we can re-assign a value still later, unless the variable is a constant (keyword final).

int temperature = 70; // Fahrenheit
float drunk = .01; // in percent
final int BOILING_POINT = 212; // a constant is final: no reassignment
// We will learn about arrays in detail later.
// 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"};


Sample Programs

If there is no class that matches your classfile name, you get an exception.
D:\java\teachjava\spring2003\session1>java BadName
Exception in thread "main" java.lang.NoClassDefFoundError: BadName

/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
   // Your program begins with a call to main().
   public static void main(String args[]) {
      System.out.println("This is a simple Java program.");
      }
}

Enclose multi-line comments inside /*      */
Put single-line comments after //

//This is a wordy Java program.
//Call this file "Wordy.java".
class Wordy {
// Your program begins with a call to main().
public static void main(String args[]) {
   int year = 2003;
   System.out.println("This is a wordy Java program.");
   System.out.println("This program uses the following:");
   System.out.println("public static void main(String args[]) {");
   System.out.println("The keyword public means this class is available for calls from outside the class.");
   System.out.println("The keyword static means no class is initiated,"
      + "\nwhich is good because I do not have a class to initiate.");
   System.out.println("The keyword void means this class does not return a value.");
   System.out.println("The keyword String means that args[] is of type String.");
   System.out.println("The variable name args[] refers to an array"
      + "\nbecause some programs take command line arguments.");
   System.out.println("The print method prints to the screen without a new line.");
   System.out.print("So the year value will appear on THIS line: ");
   System.out.print(year);
   }
}
To assign a value to a variable, use the assignment (=) operator, which looks an equals sign.
class Assignment {
   public static void main(String args[]) {
      int x, y; // variable declarations

      x = 100; // this assigns x the value 100
      y = 10;

      System.out.println("The value of x is: " + x);
      System.out.println("The value of y is: " + y);
      System.out.println("The product of x and y is: " + x*y);
      System.out.println("The dividend of x / y is: " + x/y);
      }
}
TIP: Do not confuse assignment 
  x = 4;
with testing for true
  if x == 4;
Can you find the bug?
class HelloWorldApp2 {
   public static void main(String[] args) {
   System.out.println("Hello World!); //Display the string.
   }
}
D:\java\124115\sessions\demos\2\HelloWorldApp2.java:3: unclosed string literal

Control statements

if statement

The most basic control statement is the if test.
The syntax is involves a check that the if expression evaluates to a Boolean true:

if(condition) statement;

int myNum1 = 2;
int myNum2 = 4;
if (myNum1 + myNum1 == myNum2); // returns true

Let us discuss:

What is the difference between (a) and (b)?

(a)
  if (isLeapYear == true)
(b)
  if (isLeapYear)
Answer: (a) is redundant. It is better to write (b).

 

Let's look at the ? operator: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/if.html

Shortcut if-else Statement

The ?: operator is a conditional operator that is short-hand for an if-else statement:

op1 ? op2 : op3

The ?: operator returns op2 if op1 is true or returns op3 if op1 is false.

Think of it as:
if op1 is true, return op2, else return op3

Geek Note: This three-part operator is also called a "ternary operator"

Loops

Loops allow you to take advantage of a strength of the computer, speed.

while loop

The most straightforward loop syntax is that of the while loop.

for loop

The most common loop is a for loop. The syntax is:

 for (initialization; condition; increment) statement;

Example:

The output of the while loop and the for loop is the same:


Notes:

Discussion: let's compare Do and Do While loops by looking at http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html

The special aspect of the Do While loop is ________________ .


For Loops: More Info

The follow is a standard for loop to process command-line arguments.

http://www.cafeaulait.org/course/week2/30.html

Multiple Initializers and Incrementers

Sometimes it's necessary to initialize several variables before beginning a for loop. Similarly you may want to increment more than one variable. Java lets you do this by placing a comma between the different initializers and incrementers like this:

for (int i = 1,  j = 100;  i < 100;  i = i+1, j = j-1)  {    
    System.out.println(i + j); 
}

You can't, however, include multiple test conditions, at least not with commas. The following line is illegal and will generate a compiler error.

for (int i = 1,  j = 100;  i <= 100, j > 0;  i = i-1, j = j-1) {    

To include multiple tests you need to use the boolean logic operators && and ||


What is different now?

Why doe this application fail to compile?

What does the error message mean?

InfiniteLoop2.java:9: unreachable statement
System.out.println(); // Finish the line

Does Java make infinite loops illegal?
Is there a use case for an infinite loop?


Code blocks

A block of code is whatever is within a set of curly braces.
{ // open curly brace
{ // close curly brace

{ // start of code block
  // declarations, assignments, control statements, and so on
} // end of code block

Think of a code block as a unit of code. Just as an English sentence can have many clauses and commas, but still be a single unit (the sentence), so many lines of code can belong to a single code block. A class definition resides a code block. We have seen how within a class definition code block, we can have code blocks for a for loop. An if statement can also have multiple statements within its code block.

if (s.length() > s2.length()  { // if true, execute both statements in the block
    System.out.println("s is longer than s2.");
    System.out.println("s2 is shorter than s.");
}

TIP: When you begin a code block, type both the beginning curly brace and the ending curly brace before you fill in the block with code. That way you will not forget to close your code block.

The "scope" of a variable is defined by the code block in which it resides. Scope defines the visibility of variables.

Language tokens

Parsing

What is a parser? The part of javac that prepares your source code for compilation into bytecode.

v. parsed, pars·ing, pars·es
v. tr.
  1. To break (a sentence) down into its component parts of speech with an explanation of the form, function, and syntactical relationship of each part.
  2. To describe (a word) by stating its part of speech, form, and syntactical relationships in a sentence.
  3.  
    1. To examine closely or subject to detailed analysis, especially by breaking up into components: “What are we missing by parsing the behavior of chimpanzees into the conventional categories recognized largely from our own behavior?” (Stephen Jay Gould).
    2. To make sense of; comprehend: I simply couldn't parse what you just said.
  4. Computer Science. To analyze or separate (input, for example) into more easily processed components.

v. intr.

To admit of being parsed: sentences that do not parse easily.

[Probably from Middle English pars, part of speech, from Latin pars (rtinis), part (of speech). See per-2 in Indo-European Roots.]

When you invoke the javac compiler, it parses the tokens in your source code. The parser ignores the contents of comments as well as white space. Therefore, the following are the same:

When you name identifiers (variables, methods, classes), the characters must be contiguous (no spaces), cannot start with a numeral, and cannot include operators.

Separators

CHARACTER NAME USE
;
semicolon to end a statement
.
dot operator to separate an object from one of its members (methods and properties) for the syntax object.member
( )
parenthesis to contain a list of parameters (or arguments) for a method;
to contain the condition in a control statement
{ }
curly braces to define a block of code
[ ]
brackets to declare an array and to contain assignments to an array

Key words and reserved words

You cannot use the following as identifiers in your code.

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html

true false null  
abstract double int strictfp **
boolean else interface super
break extends long switch
byte final native synchronized
case finally new this
catch float package throw
char for private throws
class goto * protected transient
const * if public try
continue implements return void
default import short volatile
do instanceof static while

Built-in methods (libraries) - core APIs

Documentation on the 1.4 APIs: http://java.sun.com/j2se/1.4.1/docs/api/index.html

The Java software development kit comes with many built-in methods. This Java environment includes these methods to support major types of functionality, such as security, XML, networking, and input and output. Having a rich set of pre-built methods and properties saves you time. Here's an example.

/* This program uses API introduced in 1.1.
   It tells you the language version of your Java.
   In my case, in United States English: en_US */

public class CurrentLanguage {
   public static void main(String[] args) {
   System.out.println(java.util.Locale.getDefault());
   }
}

Earlier, we saw that the String object has a method, length(),  for getting the length (number of characters) in the string.
An array has a property, length, that represents the numbers of elements in the array.

The Java platform offers predefined formatting for numbers: http://java.sun.com/docs/books/tutorial/java/data/numberFormat.htm

One student used the parseInt method of the Integer class to convert the strings of args[] into integers.

l

This is called conversion or type conversion. See Type Conversion.

Let's now take a tour of the API documentation: http://java.sun.com/j2se/1.4.1/docs/api/index.html


The example that follows this table of arithmetic operators uses the modulus operator (%).

Operator Name Use Description
+ addition op1 + op2 Adds op1 and op2
- subtraction op1 - op2 Subtracts op2 from op1
* multiplication op1 * op2 Multiplies op1 by op2
/ division op1 / op2 Divides op1 by op2
% modulus op1 % op2 Computes the remainder of dividing op1 by op2

The program finds the integers between 1 and 100 that are a multiple of 13.

Note that I decrement instead of increment by using -- instead of ++.

The output is:

Your homework is to write a program that has an if statement inside of a for loop, or a for loop inside of an if statement.

 =====================================

Data Types

This lecture covers the reading in Chapter 2: Data Types and Operators Data types
  • Integers
  • Floating-point
  • Characters
  • Booleans

Literals

Variables

  • declaring
  • initializing
  • scope

Type Conversion

Type Casting

Type Promotion

Arrays

  • one-dimensional
  • multidimensional

Strings


Quiz

Homework Assignment


Data types

A data type is the characteristic of a variable that determines what kind of data it can hold. Java is a strongly-typed language because it requires that every variable and expression have a type. The Java compiler checks for type compatibility among the variables to which you assign values. The Java compiler has a parser and debugger that alerts you of any type mismatch, and you have to fix it before your program will compile.

Although javac generally requires you to specify the data type, printing out the primitive types is an exception. For example, javac implicitly assigns a datatype at compile-time for the following:

System.out.println(22/7); // ints
println(22.0/7.0);  // doubles
System.out.println("22/7"); // one string

Variable Types - Primitives

A given variable is either a primitive (basic type) or an object (custom type). 
Each primitive data type has a range of values, which determines its size in memory

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/variables.html

The output is:


Integers

Whole numbers without decimals (no floating point).

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

Can be float or double.

Floating point types
float 32 bits (6 digits) 3.40282e+38 floating point (currency, temperature, percentage, length)
double 64 bits (15 digits) 1.79769e+308 double (large numbers or high precision, such as for astronomy or subatomic physics)

The java compiler expects you will perform division by using double instead of float.

Characters

Special types
char 16 bits (2 bytes) Unicode characters
(whereas other languages use 1-byte ASCII text characters)
http://www.unicode.org/unicode/standard/WhatIsUnicode.html
alphabets and numerals

Booleans

Special types
boolean Java reserves 8 bits but only uses 1 true
false

Note: These values are keywords.
logic test with if

Copy by value (primitive) versus copy by reference (object)

Java stores each primitive type in a fixed amount of memory and Java directly manipulates the values for primitives. 

However, objects and arrays do not have a standard size, and they can become large, complex, and slow to initialize.
Java economizes memory and boosts performance by manipulating these "reference types" (objects) by reference.
(Unlike C or C++, Java does not have pointers, but a variable is a named location in memory and is internally implemented by a pointer.)

Although the reference types do not have a standard size, the references to reference types do have a standard size.

Reference types differ from primitives in the way values are copied and compared.

Let's look at a diagram: http://www.cse.ucsc.edu/~charlie/classes/60g/fall96/notes/node16.html

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 by 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+0^1+0^0
8 00001000 = 2^3+0^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 = ...

Note: Unlike C and C++, Java does not have explicit pointers. Instead, a variable references an object. When you make a change to the variable that references an object, you change the original object.

Constant

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

Examples of constants

Literals

A literal is different from a variable.
Whereas a variable is name (or reference) for a storage area for a value that can change, a literal is the direct representation of a value.

Boolean true
false

(no quotation marks because a Boolean is not a string)
character any character in the 16-bit Unicode character set
a character literal is enclosed within single quotation marks
'z'
string a string object (strings are a special object type in Java)
String greeting = "Hello!";
number int yearsOnTheJob = 17;
double inflationRate = .0306;
double sum = 382.36; // sum is a variable, not a literal
String firstName = "Luke"; // string literal inside quotation marks
boolean isExpensive = false;

Here are character literals you might use:

// character literal inside single quote marks
'\n'     new line
'\t'    tab

Variables

 Declarations and assignments

Declaring a variable

            http://java.sun.com/docs/books/tutorial/java/javaOO/variables.html

Initializing a variable

The expression that initializes a variable (that assigns it a value for initial use) can be an expression with:

In this example, the declaration statement is also an expression whose return value initializes the newly declared variable.

Scope of a variable

We say, "seeing is believing". Java can only compute with variables that it can see. 
Scope is the block of code in which a variable exists and is available for use.
The scope (or visibility) of a variable depends upon WHERE you declare it. 

You might declare a variable within a block of code that is a:

local variable

A data item known within a block, but inaccessible to code outside the block. For example, any variable defined within a method is a local variable and can't be used outside the method.

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/scope.html

The output is:

QUESTION: Which line numbers define the scope of x? of y?

Sun's tutorial exposes a common error involving the concept of scope:
if (...) {
    int myInteger = 17;
    ...
}
System.out.println("The value of myInteger  = " + myInteger);    // error

The final line won't compile because the local variable myInteger is out of scope. The scope of myInteger  is the block of code between the { and }.

The myInteger variable does not exist after the closing curly brace (}) ends that block of code.

QUESTION: Can you use have an instance variable with exactly the same name as a local variable?

Scope in a for loop example

Let's discuss this example:

and its output:

Value of myInteger is: 1
Value of myInteger is: 2
3 is a multiple of 3
Value of myInteger is: 3
Value of myInteger is: 4
Value of myInteger is: 5
6 is a multiple of 3
Value of myInteger is: 6
Value of myInteger is: 7
Value of myInteger is: 8
9 is a multiple of 3
Value of myInteger is: 9

Break

Let discuss this example with break:

Type Conversion - automatic

Automatic conversion occurs when your expression involves two data types that are compatible with each other, and the conversion is widening, that is, the destination type accommodates larger values the the source type.

For example,

double myInteger = 1; // widen an integer to a double
double myFloat = 1.0; // widen a float to a double

I do not need to use all the memory it takes to store a double (64 bits) if my value is just an integer (32 bits), but Java allows me to make an assignment that involves this explicit conversion.


Example of a for loop with an if statement from http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html


Homework

Write a program that does conversion and casting.

Info about casting.


If there is extra time, let's just look at reading a file..

import java.io.*;
public class ReadFileByLine {
   public static void main(String[] args) throws IOException {
      File file=new File("test.txt");
      FileReader fr=new FileReader(file);
      BufferedReader br=new BufferedReader(fr);
      String s=null;
      while((s=br.readLine())!=null) {
         System.out.println("line: "+s);
      }
      br.close();
      fr.close();
   }
}