Ch.
5. More Data Types and Operators |
Session 5
|
For impulsive purchase, an array named mcdonalds of type fastfoodImage with 15 elements:

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.
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).
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
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)
The array class provides methods that are static.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Array.html
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);
}
}

The output is:

Using a nested for loop to populate two dimensions.

Another example of the same technique.

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.

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
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.
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
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
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 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.

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.

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 move 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.

Let's look at the ? operator, so named because it has three operands.
op1 ? op2 : op3
The two unusual tokens are the separators: ? and :
The
?:operator is a conditional operator that is short-hand for anif-elsestatement:op1 ? op2 : op3The
?:operator returnsop2ifop1is true or returnsop3ifop1is 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
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.
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
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
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)
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
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.
