Ch.
5. More Data Types and Operators week5-2014-fall-b.zip
|
Session 5
If there is extra time ... |
The JVM can call a method, finalize(), on its own thread related to memory management, which is separate from the main thread. This example also shows how to define a constructor and how to define a method.
The following illustrates the use of a static method calls (lines 40 and 42), which are OF a class rather than ON an object. Static members are stored one time in in a central place on the JVM, unlike instance variables, which have a separate copy for each instance.
An array is a collection of objects of the same type.
The syntax for allocating memory for an array is similar to that for creating other types of objects insofar as we use the new operator:
type[] identifier = new type[size-to-allocate-for-values];
For example,
HumanBeing[] originalPair = new HumanBeing[2];
To assign a value to an element in the array, we reference the element.
originalPair[0] = eve;
originalPair[1] = adam;
If we already know the value of the elements at definition time, we can initialize the array with values with specifying the size:
HumanBeing[] originalPair = { eve, adam };
Here is a primitive example:
int[] myIntArray = new int[10];
myIntArray[8] = 47; // assign a value to an element
The first array we encountered was args,
the array of Strings we can type at the command line when we launch a
program.
If we invoke the interpreter with a single arg, such as 236
java HelloWorld 236
The value 236 will be stored in args as a String.
// construct an array of type char
char[] albumName = {'H', 'e', 'l', 'p'};
The JVM stores a String internally as an array of individual characters, primitives of the the type char.
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.
SUMMARY: An array is a collection of items of the same type, whether that type is a primitive (like char, int, boolean) or a reference type (like String, Employee, or Beatle).
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.
SUMMARY: 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. Such a references causes the JVM to throw the ArrayIndexOutOfBoundsException and shown in ArrayErr.java.
An array can be declared, assigned a length, and populated.
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;
Arrays are
useful for many things. An array is an object that is also 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, such as an array, that contains multiple values (or objects).
SUMMARY: Two ways to create an array:
Here, we populate the array with a comma-separated list in curly braces, and do not specify its length. This is the array initializer syntax:
In the example above, how does Java know the length of the array of friends?
Here, we populate indexed elements after the assignment of the array length:
Note that it is not necessary to populate all the elements in an array.
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
Let's consider
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29
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)
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);
}
}
We can think of a 2-D array as being like a table with rows and columns. Here, we reference the third row and second column.
The follow example allocates three rows and four columns.
If a one-dimensional array is like a lining up of objects of the same type, a
multi-dimensional array is like a table or spreadsheets that has both rows and
columns. The syntax can be thought of as:
type[] identifier = {
{row1-value, its-column-value},
{row2-value, its-column-value}
};
Another example:
Non-populated array elements receive a default value:
By default, an array of type String or any other reference type defaults to elements with the value of null.
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.
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.
A runtime error occurs if you try to access an non-existing index.
Processing an array with an algorithm, and using population by assignment:
This version populates the array with initial values:
Alternatively, you can initialize an array without using the new operator if you populate it with a comma-delimited list.
Sorting an array with the Bubble Sort algorithm.
Because an array is an object, assignment of values can occur by reference.
Because an array is a reference type, it can have a field. 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.
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 http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html and http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html.
Is it more efficient to use a reference to an existing string or to create a new string? Let's check with TimerDemoForString.java.
With J2SE 5, it is no longer necessary to use the array length field to process each index exactly one time. The for each style loop has neither an explicit counter, nor a test condition. It will attempt to process ALL the elements in an array.
An example that iterates a String array:
Another example:
Use cases for the for each style loop involve processing ALL the elements in an array, and include getting the average value, searching, finding minimum or maximum value.
However, the for each style loop cannot be used in many cases, such as if want to reassign values in an array, or if you need to track two counters.
for(int i = 0; int k = myArray.maxValue; i < myArray.length; i--, k--)
SUMMARY: Strings are objects, which means they inherit methods from the java.lang.String class.
The String methods are listed in the APIs at http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#method_summary
and among the commonly-used methods are:
curie
marie
polonium
53
6.5
10.75
8.5
Mohandas
Karamchand
Gandhi
Esquire
G
a
n
d
h
i
This example tests whether a string contains a certain sequence of characters by using the contains method of the String class - http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains%28java.lang.CharSequence%29
If the String contains any sequence of characters in the wordsToFilter array, we print an entirely different string.
See also ContentFilterDemoWithDoWhile.java
The trim method removes white space, as shown in StringTrimDemo.java:
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, that is,
that the two
references point 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.
Use methods of the String class on string objects:
Using the substring property of a String, where the first argument is the starting char and the second argument is the ending char.
Which methods of the String class do we use in StringsDemo.java?
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.
SUMMARY: The value of a String cannot change, and this is known as String immutability. 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 and its contents are eligible for garbage collection. The variable name that points to the old string can be reused to point to a new string.
An analogy might be the state capital of California, which, during the Gold Rush, moved closer and closer to the gold. The variable name of "capital" remained but each time it referred to a different object, that is, a different city name:
String capital = Monterrey; // 1777
String capital = San Jose; // 1849
String capital = Vallejo; // 1852
String capital = Benicia; // 1853
String capital = Sacramento; // 1854;
You can also create a new string with equivalent contents.
SUMMARY: Java distinguishes between String equivalence and String instance. The equal to operator ( == ) determines if the same location of memory is used for two references to a String, that is, two references to the same String instance or object. 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.
SUMMARY: the args array comes from any command-line arguments passed in when the JVM launches the bytecode for main. This array is of type String, even if the arguments appear to be numbers. The args array is usually empty and unused.
We learned about the switch program control statement at http://www.write-technical.com/126581/session3/session3.htm#switch
Now, we can see an enhancement to Java to allow a string to be tested in the case statements.
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.
Let's look at the ? operator, so named because it has three operands.
op1 ? op2 : op3
The two unusual tokens are the separators: ? and :
SUMMARY: The ?:
operator is a
conditional operator that asks one boolean question and offers an assignment for
both the true and false cases.
result = op1 ? op2 : op3
The ?:
operator assigns using op2
if
op1
is true. It assigns using op3
if op1
is false.
Think of the ternary statement as short-hand for an
if
-else
statement:
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);
}
}
The output is:
14
13
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.
Example 3
=================================================================================================
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.
The StringBuilder class allows a String-like object to change the characters it contains, and the number of characters it contains, without automatically creating a new object. To do so, use the append() and insert() methods. See http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
Note that the StringBuilder object, unlike a String, can be changed. The proof is that the internal identifier remains the same:
The internal buffer of the StringBuilder increases from 20 to 42 to 86.
sb.hashCode() = 366712642
The capacity of this StringBuilder object is
20 characters.
this StringBuilder contains 1234
After append = 1234appended
Here we want at least 21 characters so that the internal buffer expands beyond t
he original 20
366712642
The NEW capacity is 42
characters.
sb.hashCode() = 366712642
Here we want 43 characters so that the internal buffer expands beyond 42
The NEW capacity is 86
characters.
123456789012345678901231234 INSERTEDappended
To get a String with the same characters as those in the StringBuilder, use the
toString() method 123456789012345678901231234 INSERTEDappended