if ( array.length > 0 ) { . . . System.out.println("The average is: " + total / array.length ); } else System.out.println("The array contains no elements." );
Are the following two arrays equal?
int[] arrayA = { 1, 2, 3, 4 };
int[] arrayB = { 7, 8, 9};
Obviously not.
Are these two arrays equal?
int[] arrayC = { 1, 2, 3, 4 };
int[] arrayD = { 4, 3, 2, 1 };
Less obvious, but ordinarily they would not be regarded as equal.
What about these two arrays: are they equal?
int[] arrayE = { 1, 2, 3, 4 };
int[] arrayF = { 1, 2, 3, 4 };
Here, it depends on what you mean by "equal".
The object referred to by the variable arrayE is not the same
object that is referred to by the variable arrayF.
The "alias detector" arrayE == arrayF returns false.
class ArrayEquality
{
public static void main ( String[] args )
{
int[] arrayE = { 1, 2, 3, 4 };
int[] arrayF = { 1, 2, 3, 4 };
if (arrayE == arrayF)
System.out.println( "Equal" );
else
System.out.println( "NOT Equal" );
}
}
Output:
NOT Equal
You have seen this situation before, with two separate String
objects containing the same characters:
class StringEquality
{
public static void main ( String[] args )
{
String stringE = new String( "Red Delicious"); // create a string object
String stringF = new String( "Red Delicious"); // create another string object
if (stringE == stringF)
System.out.println( "Equal" );
else
System.out.println( "NOT Equal" );
}
}
Output:
NOT Equal
There are two individual objects,
so the object reference in stringE is not
== to the object reference in stringF.
Confusion Alert! (review of Chapter 43)
String stringG = "Red Delicious" ; // create a String literal, stringG points to it
String stringH = "Red Delicious" ; // point stringH to the same String literal
if (stringG == stringH)
System.out.println( "One Literal" );
else
System.out.println( "NOT Equal" );
What does the above print?