(syllabus and calendar)

Ch. 5. More Data Types and Operators
pp. 151-200

examples-5th-week.zip

Session 5


Quiz

Arrays

An array is a collection of items of the same type.

// construct an array of type char
char[] albumName = {'h', 'e', 'l', 'p'};
   

A String is implemented internally as an array of characters.

String albumName = "help";

is essentially the same as

char[] albumName = {'h', 'e', 'l', 'p'};

as here demonstrated by the acrobatic contortions of John, Ringo, George (backwardly), and Paul.

For impulsive purchase, a two-dimensional array named mcdonalds of type fastfoodImage with 15 elements:

With its 5 rows and 3 columns, this could be represented as fastfoodImage[5][3]

For scientific analysis, a three-dimensional array that is 9 by 9 by 9:

How many arrays are in this photograph?

 

An array stores multiple variables 

Examples of arrays

http://www.developer.com/java/other/article.php/1268901
Array objects encapsulate a group of variables, which don't have individual names. They are accessed using positive integer index values. The integer indices of a Java array object always extend from 0 to (n-1) where n is the length of the array encapsulated in the object. TIP: Remember that in Java, an array is zero-based, and if you try to access an array of, say, 5 elements at the 5th index, well, there is no 5th index, only 0 through 4.

one-dimensional population and length field

Line 4 declares the array named month_days to store a set of values of type int.
Line 5 creates the array with 12 elements. 12 is the length of this array, that is, its capacity for storing element values. You cannot reset the length of an array, but you can get its length field with this syntax: arrayName.length; For example, month_days.length;
Lines 6 through 17 populate the array with integer values.
Line 19 gets the number of elements in an array by using the static length field of the array object.

Arrays are useful for many things. An array is a collection. One use of an array is as the return value of a method. In Java, a method can only return one value or object. What if you method calculates two or more values? It is possible to have the method return a collection object that contains multiple values (or objects).

Declare versus declare and populate

By the way, there is more than way to create an array:

In the example above, how does Java know the length of the array of friends?

The output is:

I never assigned the value of null of the String at index 3. How does Java determine the value is null?
What kind of array does the following photograph show?
One way to perceive the bowling pins is as a ragged array (4, 3, 2, 1).
Another way is to see a 4x4 array with some nulls indices.

Arrays are objects that can be created in any of three ways:

example:s

The size of an array is immutable and available through its static instance variable: array_name.length

Review

To review, you can populate an array in the same statement as the declaration by using a comma delimiter for the element at each index..

Or, you can populate the array with a series of indexed assignments after the declaration statement.

The arraycopy method belongs to what class? Does it belong to an object? What does the arraycopy method do?

Why would the arraycopy  method be a static method on the System object?

public static void arraycopy(Object src,
                             int srcPos,
                             Object dest,
                             int destPos,
                             int length)

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)

The array class provides methods that are static.

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Array.html

Arrays have the length property

Every instance of the Array class has a property called length.
The length of an array is NOT necessarily the number of values in the array.
The length of an array is the total possible memory slots (elements) available for holding values or objects.
The length is the capacity, not the contents. A typical egg carton is an array with what length?

What is the output of this application?

class MyArray {
    public static void main(String[] args) {
        int myArray[]= {25, 35, 85};
        System.out.println(myArray.length);
    }
}

multidimensional (2d)

The output is:

Two-dimensional array

Using a nested for loop to populate two dimensions.

Another example of the same technique.

Default values

By default, an array of type int defaults to elements with the value 0, and an array of type boolean defaults to elements with the value false.

 

min and max: -978 100123

Alternatively, you can initialize an array without using the new operator if you populate it with a comma-delimited list.

Array - populating an array

Arrays in Java are zero-based for referencing an element, but the counting of the number of elements in the length field begins with 1.
Therefore, arrayName.[arrayName.length - 1] references the final element. 

Here's the relevant API method for getting to a location on a String: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#charAt(int)

A runtime error occurs if you try to access an non-existing index.

Sorting an array with the Bubble Sort algorithm.

An irregular or ragged array

Initializing multiple dimensions of a multi-dimensional array.

Because an array is an object, assignment of values can occur by reference.

Using the length field, which represents the number of elements the array can hold. For loops often use the length of an array as the conditional test. This ensures each element is accessed exactly one time.

Because an array is zero-based, the last element (whether populated or not) is at the index that corresponds to array.length - 1.

The program takes advantage of the length field that is available on all arrays.

Oddly enough, this fundamental and useful field of the class Array is NOT documented as a final field at http://java.sun.com/javase/6/docs/api/java/lang/reflect/Array.html. The length is final (constant, immutable). You cannot change the length of an array. If you need something like an array with a variable length, see java.util.Vector at http://java.sun.com/javase/6/docs/api/java/util/Vector.html. Sun does explain the length field of an array at http://java.sun.com/docs/books/tutorial/java/data/arraybasics.html and http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html

for-each style for loop (p. 172)

With J2SE 5, it is no longer necessary to use the array length field to process each index exactly one time.

An example that iterates a String array:

Getting the average value, searching, finding minimum or maximum value: all these require processing all the elements in an array.


Strings are objects

Strings are objects, which means they inherit methods from the java.lang.String class.

Let's review this example:

Three ways to construct a String:

The String class provides APIs for operations.

The equals method checks for the same sequences of chars. If so, the two strings are equivalent.
If you use == to compare two strings, you are checking for identity, two references to the same string object.

An array can store String objects.

The default value of a String in an array of Strings is not empty String but null. Any object is null if it has no value assigned to it.


Using the substring property of a String, where the first argument is the starting char and the second argument is the ending char.

The follow example of a looping program uses the length field of the Array class and the charAt method of the String class.

The output is:

The program takes advantage of the length property available on all arrays.

Oddly enough, this fundamental and useful field of the class Array is NOT documented at http://java.sun.com/javase/6/docs/api/java/lang/reflect/Array.html.
Sun does explain it in the Tutorial:   http://java.sun.com/docs/books/tutorial/java/data/arraybasics.html

concatenating Strings

In Java, operators cannot be overloaded. One exception is that the addition operator (+) is overloaded for the concatenation (the stringing together) of Strings.

The output is:

First String
Second String
First String and Second String

The output is:

Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3

String class does NOT include println method

Note: http://download.oracle.com/javase/6/docs/api/java/lang/String.html lists all the methods of the String class. Even though the System.out.println method has a signature that accepts a String as input, that is, as a runtime argument, println is NOT a member of the String class.


Immutability of Strings

The value of a String cannot change. When you use the assignment operator (=) to create a new String with same identifier as the old String, the old String is replaced by a new String. The old String can no longer be accessed. However, it might be easy to create a new string with equivalent contents. The equal to operator ( = = ) determines if the same location of memory is used for two references to a String. The equals method determines if two Strings store an equivalent sequence of characters.


Command-line arguments

The output is:

args[0]: sky
args[1]: is
args[2]: blue
args[3]: 4
args[4]: you

In the following, args[0] is the String "Tom", which is passed in at the command-line without quotation marks.


Bitwise operators

A feature of many computer languages is the ability to operator on low-level data directly at the bit-level, the raw zeros and ones. Java supports this, although it does run counter to the general philosophy of high-level object oriented design. The primitive types of whole numbers (int, char, byte, long, short) can have their bits manipulated. Whereas a String has the toLowerCase method, a char has no method. Therefore, the bitwise operation is legitimate. Here, the bitwise operator is | and it moves the char 32 spaces higher in the ASCII/Unicode table by setting the 6th bit. 2 to the 6th power of 2 = 32.

The bitwise operator ~ sets any bit to its opposite value.


Ternary Operator - ?

Let's look at the ? operator, so named because it has three operands.

op1 ? op2 : op3

The two unusual tokens are the separators: ? and :

  1. Ask a boolean question represented by op1 that ends with the ?
  2. If the answer is true, return the next operator, op2.
  3. else skip to the : and return the final operator, op3.

Abbreviated 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. It returns op3 if op1 is false.

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

The ternary operator is a terse way of handling if/else logic. You ask a question that can be answered true or false. Depending on the answer, something happens or not.

The syntax is compact and prone to bugs, but it does reduce typing.

Example 1

class TernaryOperatorEquivalentToIfElse
{
    public static void main(String[] args)
    {
        int a, b, result; // declare three of same type using comma-delimited list
        a = b = result = 13; // initialize all to 13

        if(a + 1 > b)
    {
        result = a + 1;
    }
    else
    {
        result = b;
    }
    System.out.println(result);

    // equivalent logic with ternary operator
    result = a > b ? a + 1 : b;
    System.out.println(result);
    }
}

Example 2
Here, we ask if i equals zero. If so, we execute the if statement. If not, we skip the if statement execution and avoid an error. The equivalent if, else logic would be:
if i != 0, consider the condition true and execute the following line. If i == 0, skip execution of the following line.

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

Preview of IO.
Let's look at this example:

 

Sample output is:

Enter the average number of days on vacation in Hawaii 5.5
Enter the average number of coconut drinks people on vacation in Hawaii consume
each day 3.33
The average number of days on vacation in Hawaii : 5.5
The average number of coconut drinks people consume each day: 3.33
18.315



Object casting, converting, comparing

Casting objects

You can cast an object to another class if the two classes are related by inheritance.

For example, all objects inherit from the superclass Object.
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Object.html

Therefore, all objects have a GetClass() method.
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Object.html#getClass()

I do not need to make an explicit cast for my string object--in this case the command line array of strings, or string array--to use methods it inherits from its superclass(es).

The output is:

The class of [Ljava.lang.String;@108786b is [Ljava.lang.String;
The class of java.lang.Object@119c082 is java.lang.Object

Another example in which we create a custom object type.

implicit upcasting versus explicit downcasting

You do not need an explicit cast when upcasting objects, but you do need an explicit cast when downcasting objects.
For example, this example casts an object as a string.
Object is higher in the class hierarchy than String, so casting an object as a string is downcasting.

String s = "Heeeeeeeeere's Johnny";
Object o = s; // implicit upcast, no casting syntax needed because all strings inherit from the Object superclass
String sz = (String)o; // explicit downcast, need casting syntax because String is a subclass of Object

The instanceof operator

You can use the instanceof  operator to test an object's class before doing a downcast:

String s = "Heeeeeeeeere's Johnny";
Object o = s;
String sz;
if (o instanceof String) {
   sz = (String)o;
}

The instanceof operator tests whether its first operand is an instance of its second.

op1 instanceof op2

op1 must be the name of an object and op2 must be the name of a class. An object is considered to be an instance of a class if that object directly or indirectly descends from that class.

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/other.html
Here, the instanceof operator determines whether its first operand is an instance of its second operand.

The output is:

null true
false
true

Converting objects

We have seen casting among the primitive types, such as between int and double, which are related as primitives.
We also saw that all object are related, which enables upcasting and downcasting among them.
Converting is the translation between unrelated types, that is, of a primitive type to an object type, or of an object type to a primitive type, which you cannot do by casting. 
Unlike a cast, the runtime does not know enough about the types to do this automatically. 
Some code must be written to handle the conversion

Suppose that you have been storing zip codes as strings (which are objects in Java), but now you need to treat those zip codes as integers so that you can sort them as numbers more effectively.
You can use an method of the Integer class to pass in a string argument and get integer output.
In effect, the following example converts a string object into a integer primitive.

or
String stringZipCode = "94568"; // stringZipCode is a String object
int intZip = Integer.parseInt(myZipCode); // intZip is a primitive
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Integer.html

Each primitive type has a corresponding "wrapper" class. Why?

To convert an integer primitive into an object of its corresponding Integer class:

The output is:

The class of which 90103 is an instance is java.lang.Integer
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Integer.html#Integer(int)

The most common type of conversion is to and from a String. 
The java.lang.Object package defines the toString() method with a simple default implementation. 
Many classes override this implementation to provide a translation that preserves the object's content.
For example, an XML document might use the toString() method.

Suppose you want to convert the user's command line argument into an integer.

 user_input = Integer.parseInt(args[i]);
 // compare new input argument with current max number
 if (user_input > max_number) 

Comparing Objects

java.lang.Object defines an equals() method, but the default implementation is simply a = = test. 

When you compare Strings, the = = operator tests for identical objects.
More likely, you want to test for identical values being stored in the String variables.
Every String object has an equals() method for this test of equivalent values being stored in two string variables.

Whereas line 5 creates a second reference (or variable) to the original object, line 15 reassigns that variable to a new and different object.

The output is:

Contents of s1: Jimi Hendrix
Contents of s2: Jimi Hendrix
Do s1 and s2 refer to the same object? use s1 == s2) true
Do s1 and s2 have equivalent values? use s1.equals(s2) true
You created a new s2 and assigned it the value of s1, so s2 now refers to a 
different object even if the values are equivalent.
Contents of s1: Jimi Hendrix
Contents of s2: Jimi Hendrix
Do s1 and s2 refer to the same object? use s1 == s2) false
Do s1 and s2 have equivalent values? use s1.equals(s2) true

Review with a slightly different example

java.lang.Object defines an equals() method, but the default implementation is a = = test. 
Some objects override this method (which is polymorphism applied to inheritance).

When you compare Strings, the = = operator tests for identical objects.
However, generally you want to test for identical values being stored in the String variables.
Every String object has an equals() method for this test of equivalent values being stored in two string variables.

Whereas line 5 creates a second reference (or variable) to the original object, line 11 reassigns that variable to a new and different object.


Quiz: Session 5

  1. An array is a collection of variables, all of which must be of the same _______.

  2. Write the code that declares that an unpopulated array of type String named daysOfWeek contains 7 elements.

  3. Write one line of code that declares and populates the String array daysOfWeek.

  4. Write a for each loop that prints the Strings in daysOfWeek.

  5. Why does this program crash?

  6. If you assign a new set of characters to a String variable, does Java discard the original String?

  7. What is the return type of String.equals(String str) method?

  8. In the main method, what does args contain?

  9. Rewrite the following using if and else:
    x < 0 ? y = 10 : y = 20;

  10. The ? operator returns the result of its third statement if the result of the first statement is _________.