Results 1 to 1 of 1
  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Posts
    64
    Rep Power
    0

    Default Tutorial:Review of Java Operators for the Java Certification Exam

    In this article, we will provide an overview of Java Operators. We will describe the use of Java operators in Java for doing arithmetic calculations including integer, floating, bitwise and logical calculations, This is part of a larger series of articles to help you prepare for the java associate exam. The previous article in the series was, "Tutorial:Review of Java Syntax for the Java Certification Exam”.

    Arithmetic Calculations

    You store the result of a calculation in a variable by using an assignment statement. An assignment statement consists of three elements: the name of the variable where you want the result stored; the assignment operator, =, that indicates that this is indeed an assignment operation; and an arithmetic expression that defines the calculation you want to perform to produce the result. The whole thing is terminated by a semicolon that marks the end of the assignment statement. Here's a simple example of an assignment statement:

    Java Code: Calculate the number of containers
    numContainer = numBaskets + numBags;
    When this statement executes, the value of the expression to the right of the assignment operator, =, is calculated, and the result is stored in the variable that appears to the left of the = sign. In this case, the values stored in the variables numBaskets and numBags are added together, and the result is stored in the variable numContainer. You have to declare and initialize all three variables before using this assignment statement. For a simple assignments of a constant value to a variable of type short or byte, the constant is stored as the type of the variable on the left of the =, rather than type int. For example:

    Java Code: Simple Assignment
    short value = 0; 
    value = 10;
    Here you have a declaration statement for the variable value, followed by an assignment statement. When the declaration executes, it allocates space for the variable value and arranges for its initial value to be 0. The assignment statement that follows the declaration statement needs to have 10 available as an integer literal of type short, occupying 2 bytes, because value is of type short. The compiler converts the literal value 10, which is of type int, to type short. The value 10 is then copied to the variable value. We will look more in detail at how you perform calculations.

    Using Operators

    Java includes many operators, from ordinary mathematical operators such as a minus sign (-) to operators that are specific to object-oriented programming such as instanceof. The list of operators are shown in the following table:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-javaoperators.jpg
    Figure: Java Operators

    Operator Precedence

    The key thing to remember about operator precedence is the term PEMDAS for Parentheses, Exponent, Multiplication,Division, Addition, and Subtraction. This operator precedence works with algebra equations as we know to resolve parentheses before resolving exponents and so on.

    This is also true in Java despite it having a lot more than six operators. Java also has some operators that have the same level of precedence. In these cases, precedence proceeds from left to right for binary operators (except assignment operators) and right to left for assignment operators. That's probably as clear as mud, but we get to some examples shortly that clarify the order of operations and identify some of the problem spots where people often trip.

    The Missing Operator: Parentheses

    Parentheses aren't in the list of Java operators, but they act as an operator with the highest precedence. Anything in parentheses is resolved first. When a line has several sets of parentheses, they are resolved from innermost to outermost and from left to right. Below are some examples of its use in the listing below:

    Java Code: Parentheses as an operator
    System.out.println(2 + 4 / 2); 
    // division processed first, so prints 4 
    System.out.println((2 + 4) / 2); 
    // addition processed first, so prints 3 
    System.out.println((2 + 4) / 3 * 2); 
    // prints 4, not 1 – see below for why 
    System.out.println((2 + 4) / (3 * 2)); 
    // prints 1
    System.out.println((2 + 4) / (2 * 2)); 
    // prints 1 – note the truncation 
    System.out.println((2.0 + 4.0) / (2.0 * 2.0)); // prints 1.5
    As a rule, remember to use parentheses to clarify your code and to ensure the proper order for your operations. If you can gain clarity by splitting a line onto multiple lines to make your operations clear for other developers as well as yourself when you return to the code at a later date, then do so.

    Postfix Operators

    The term postfix has a number of meanings in mathematics, linguistics, and other fields. In computer science, it means an operator that follows an expression. Java's two postfix operators increment (increase by one) and decrement (decrease by one) values. The listing below shows examples of postfix operators:

    Java Code: Postfix operators
    private int getC() { 
       int c = 0; 
       c++;  // c = 1 now 
       c--; // c = 0 now 
       return c++; //returns 0;
    }
    The listing returns 0 because the postfix operators first return the original value and then assign the new value to the variable. To fix it, use the unary ++ operator before the expression rather than the postfix operator after the expression or move your return statement to its own line. Parentheses around the expression (c++) do not make this method return 1, because c would have been set to 0 within the parentheses.

    Unary Operators

    Strictly speaking, a unary operator is an operator that takes just one operand. By that definition, the postfix operators are also unary operators. However, Java distinguishes between the postfix operators and the other unary operators. Remember the postfix operators return the value before the postfix operation has been applied. The unary operators return their values after the operator has been applied. The table below describes the unary operators:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-unaryoperators.jpg
    Table: Unary Operators

    In the listing below is a series of examples using unary operators:

    Java Code: Unary operators
    byte a = 0; 
    ++a; // unary prefix increment operator - now a has a value of 1 
    --a; // unary prefix decrement operator - back to 0 
    byte b = +1; // unary plus operator (unnecessary) 
    byte c = -1; // unary minus operator to create a negative number 
    System.out.println(~b); // bitwise complement operator - prints -2 
    System.out.println(~c); // bitwise complement operator - prints 0 
    boolean myTeamWon = false; 
    System.out.println(!myTeamWon); // logical complement operator - prints true
    Understanding the Bitwise Complement Operator

    Java (and all programming languages) store values in one or more bytes, and each byte consists of 32 bits. When we talk about bytes in this context, we mean the units computers use for memory. That's not the same as Java's data type called “Byte” (which has a minimum value of -128 and a maximum value of of 127). The JVM stores a value of one as the following binary string: 00000000000000000000000000000001 (a 32-bit binary value that consists of 31 zeroes and a single one). When you use the bitwise complement operator on it, the JVM turns all the zeroes into ones and all the ones into zeroes, resulting in 11111111111111111111111111111110, which evaluates to -2. Similarly, -1 in binary is 11111111111111111111111111111111. Because that's all ones, the bitwise complement operator turns it to all zeroes, so its value is 0.

    The bitwise complement operator promotes the values of byte, short, and char variables to 32 bits before applying the ~ operator. The result of the operator is an int in those cases. That's why the binary strings have 32 characters. This process is called unary numeric promotion. Examples are shown in the listing below:

    Java Code: Unary numeric promotion
    byte a = 0; 
    Byte b = new Byte(a); // no problem 
    Byte c = new Byte(~a); // won't compile because the Byte constructor cannot accept an int int d = ~a; // no problem
    Casting

    When you need a variable of one type to be a variable of another type, in Java you create a new variable and convert the existing variable into the new variable's type. This process is known as casting, and Java provides an operator of sorts for doing it. The casting operator differs according to the data type to which you're casting. Specifically, you wrap parentheses around the name of the type to which you're casting and put that operator before the value you want to cast. Casting is often necessary to prevent the compiler from throwing errors when we convert one data type to another. The listing below provides examples of casting:

    Java Code: Casting
    // Cast a byte to an int 
    byte b = 123; 
    int bInt = b; // no casting necessary
    
    // Cast an int to a short 
    int i = 123; 
    short s = (short) i; //(short) is the casting operator – beware of values that are too large
    
    // Cast a float to an int 
    float f = 12.34f; 
    int floatInt = (int) f; // floatInt = 12 – the original value is truncated
    
    // Cast a char to a String – oops 
    char c = 'c'; // can't directly cast a char to a string 
    Character cChar = new Character(c); // so get a Character wrapper object for our char String s = cChar.toString(); // and get a String object from the wrapper
    The fourth example is not really a cast, but it shows how to get from a primitive (a char in this case) to a String. The same pattern applies for all the primitives: First get a wrapper for the primitive and then use the wrapper's toString method. Defensive coding is good practice for narrowing casts. It is a good idea any time you can't be sure the provided value won't cause a problem. In fact, in some kinds of applications such as distributed applications it's standard practice to validate all the arguments to a method. The listing below provides an example of defensive coding for a narrowing cast from an int to a byte:

    Java Code: Defensive coding for a narrowing cast
    private static byte intToByte(int i) { 
       if (i > Byte.MAX_VALUE || i < Byte.MIN_VALUE) {
          throw new IllegalArgumentException("integer argument " + 
    		"is too large or too small to cast to a byte");
       }
       return (byte) i;
    }
    Multiplicative Operators

    Java has three multiplicative operators: multiplication (*), division (/), and modulus (%). There's no implicit order of operations between these three operators. To the JVM, they all have the same precedence. Therefore the JVM processes them from left to right. Remember that Java isn't algebra, though some of the operators and concepts exist in both. Multiplication and division are obvious enough, but some may not know the modulus operator. Below is an example:

    Java Code: Modulus operator examples
    int a = 9; 
    int b = 2; 
    int c = a % b; 
    // c equals 1 
    float f = 1.9f; 
    float g = 0.4f; 
    float h = f % g; 
    // h equals 0.3 – but beware of rounding
    The listing shows that the modulus operator divides the first operand by the second operand and returns the remainder.

    Additive Operators

    There are a number of subtleties worth noting when used in a Java application. As with the multiplicative operators, the order of precedence for the additive operators is the same, so they get processed from left to right, even when the minus precedes the plus operator on a line. This isn’t important. However, there are some times that it does matter.

    Note that the plus sign is the string concatenation operator. This has the form someString + someOtherString = aThirdString. The addition operator and the string concatenation operator are different operators despite using the same character. The JVM figures whether to use a plus sign as the addition operator or as the string concatenation operator by context. If the JVM determines that the context is numeric, it performs addition operations. If the JVM determines that the context is textual, it performs concatenation operations. The listing below demonstrates what happens when the JVM encounters different contexts:

    Java Code: The ShiftDemo context switching example
    int a = 1; 
    int b = 2; 
    int c = 3; 
    System.out.println(a + b + c); 
    System.out.println("a + b + c = " + a + b + c); 
    System.out.println("a + b + c = " + (a + b + c));
    When run in a program, that code produces the following output:
    XML Code: Contect switching example output
    6 
    a + b + c = 123 
    a+b+c= 6
    The context for the first line is numeric, because the first value processed by the println method is numeric. The context for the second line is textual because the first value processed by the println method is a String literal. The third line gets the right value because the parentheses force the addition to happen first, even though the context is textual.

    Shift Operators

    The shift operators take us back to working with bits. The shift operators require two operands: The integral (no floating-point values allowed) value to shift and the number of places to shift the bits that comprise the value. The signed left shift operator (<<) shifts bits to the left. The signed right shift operator (>>) shifts bits to the right. The signed right shift operator (>>>) shifts bits to the right and fills the left bits with zeroes. The listing below show what the shift operators do to the value of an int variable:

    Java Code: ShiftDemo package
     com.acme.java.examples.shiftDemo; 
    public class ShiftDemo {
       public static void main(String[] args) throws Exception { 
          int b = 127; 
          System.out.println("b: " + b);
          System.out.println("b as binary: " + Integer.toBinaryString(b)); 
          String leftShiftString = Integer.toBinaryString(b<<3); 
          System.out.println("binary after signed left shifting 3 places: " + leftShiftString); 
          System.out.println("value of b after signed shifting left 3 places: " + Integer.parseInt(leftShiftString, 2)); 
          String rightShiftString = Integer.toBinaryString(b>>3); 
          System.out.println("binary after signed shifting right 3 places: " + rightShiftString); 
          System.out.println("value of b after signed shifting right 3 places: " + Integer.parseInt(rightShiftString, 2)); 
          String unsignedRightShiftString = Integer.toBinaryString(b>>>3); 
          System.out.println("binary after unsigned shifting right 3 places: " + unsignedRightShiftString); 
          System.out.println("value of b after unsigned shifting right 3 places: " + Integer.parseInt(unsignedRightShiftString, 2)); 
           b = -128; 
           System.out.println("Resetting b to " + b); 
           System.out.println("b as binary: " + Integer.toBinaryString(b)); 
           unsignedRightShiftString = Integer.toBinaryString(b>>>3); 
           System.out.println("binary after unsigned shifting right 3 places: " + unsignedRightShiftString); 
           System.out.println("value of b after unsigned shifting right 3 places: " + Integer.parseInt(unsignedRightShiftString, 2));
        }
    }
    The output for ShiftDemo is the following:

    XML Code: Shift Demo Output
    b: 127 
    b as binary: 1111111; 
    binary after signed left shifting 3 places: 1111111000 
    value of b after signed shifting left 3 places: 1016 
    binary after signed shifting right 3 places: 1111 
    value of b after signed shifting right 3 places: 15 
    binary after unsigned shifting right 3 places: 1111 
    value of b after unsigned shifting right 3 places: 15 
    Resetting b to -128 b as binary: 11111111111111111111111110000000 
    binary after unsigned shifting right 3 places: 11111111111111111111111110000 
    value of b after unsigned shifting right 3 places: 536870896
    You use shifting if you’re sure that shifting produces the values you want or if you happen to be working with values that aren't really values but rather collections of switches such as graphics settings. The shift operators provides efficient ways to manipulate those values or switches.

    Relational Operators

    The relational operators compare things to one another. In particular, they determine whether one value is greater than, less than, equal to, or not equal to another value. For the relational operators to work, the items being compared have to be comparable. In Java, this means they need to be comparable for the primitives. Thus, you can compare an int to a float and get a meaningful result (i.e. the JVM promotes the int to a float and then does the comparison). So long as one or the other can be cast to the other value, Java can meaningfully compare primitives. > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to) all work on primitives, but they don't work on objects. Conversely, instanceof works on objects but not on primitives. Java does provide ways to compare objects to one another, but not through any operators. The listing below illustrates the comparison of primitives:

    Java Code: Comparing primitives
    int a = 0; 
    float b = 1.0f; 
    System.out.println(a > b);
    That bit of code prints “false” in the console. The instanceof operator is subtle as the class that extends another class is also an instance of the parent class. Consider the following small program, implemented in three classes:

    Java Code: instanceof test
    package com.acme.java.examples.instanceofTest;
    public class Person { 
       String firstName; 
       String lastName;
       public Person (String firstName, String lastName) { 
          this.firstName = firstName;
          this.lastName = lastName;
       }
    }
    
    package com.acme.java.examples.instanceofTest;
    
    public class Worker extends Person { 
       String companyName;
    
       public Worker (String firstName, String lastName, String companyName) { 
          super(firstName, lastName);
          this.companyName = companyName;
    }
    
    package com.acme.java.examples.instanceofTest; 
       public class InstanceofTest {
      
          public static void main(String[] args) { 
             Worker Worker = new Worker("Joe", "Bloggs", "Acme"); 
             System.out.println(worker instanceof worker); 
             System.out.println(student instanceof Person);
          }
    }
    Both print statements print “true” in the console. After all, a student is a person. The nature of object-oriented programming, where one class always extends another, demands that the instanceof operator works this way.

    Equality Operators

    Java has two equality operators: == (equals) and != (not equals). The equality operator (==) and the inequality operator (!=)work the same way each is the antithesis of the other.
    Java uses a single equal sign as the base assignment operator so it can't use a single equal sign for comparisons. Consequently, Java uses two equal signs.

    For primitives, the equality operators work exactly as expected comparing the values, however, for objects, the equality operators indicate whether two references refer to the same instance. The listing below shows examples of the equality operators:

    Java Code: Equality operator example
    int a = 0; 
    int b = 1; 
    String s = "s"; 
    String sToo = "s"; 
    System.out.println(a == b); 
    System.out.println(s == sToo);
    The console will print “true” for a == b and “false” for s == sToo as s and sToo are references to different instances of the String object despite having the same value. They are not equal in the eyes of the equality operators. This is the same for s == “s”, which prints false, because the string literal produces yet another instance of the String class.

    To compare objects such as instances of the String class, Java programmers use the equals method. Any object whose instances can be compared to each other should implement the equals method that is defined in the Object class. This is the case for the String class. The listing below compares instances of String:

    Java Code: Testing equality for objects
    String s = "s"; 
    String sToo = "s"; 
    System.out.println(s.equals(sToo)); 
    System.out.println(s.equals("s"));
    The console will show that both print statements will produce “true” in the console.

    Bitwise Operations

    All integer variables are represented internally as binary numbers. A value of type int consists of 32 binary digits, known to us computer fans as bits. You can operate on the bits that make up integer values using the bitwise operators, of which there are four available. They are shown in the following table:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-bitwiseoperators.jpg
    Table: Bitwise Operators

    The following table shows examples of the effect of each of these operators:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-bitwiseopexamples.jpg
    Table: Operator Examples

    This shows the binary digits that make up the operands a and b and the results of four bitwise operations. The three binary bitwise operations produces the result by applying the operation to each corresponding pair of bits from its operands in turn. The complement operator just flips the state of each bit in its operand so that 0 changes to 1 and 1 changes to 0 in the value that results.

    Using the AND and OR Operators

    The | operator forces a bit to be 1 in a variable when the corresponding mask bit is 1, and each mask bit that is 0 leaves the corresponding bit unchanged. Thus you can use the | operator to set particular bits in a variable to 1.

    The & and | operators are the most frequently used of the bitwise operators, mainly for dealing with variables where the individual bits are used as state indicators of some kind—for things that can be either true or false, or on or off. You could use a single bit as a state indicator determining whether something should be displayed, with the bit as 1, or not displayed, with the bit as 0. To take a simple example, to select the third bit from the right in the int variable indicators, you can write the following:

    Java Code: Selecting 3rd bit, 0x4 in hexadecimal
     thirdBit = indicators & 0b0100;
    The third bit of the variable thirdBit is the same as the third bit in indicators and all the other bits is zero. I can illustrate how this works by assuming the variable indicators contains the binary value 0b1111_1111_0000_1111, which you could also write as the hexadecimal value 0xFF07:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-bitwiseex0xff07.jpg
    Table: Bitwise Example using 0xFF07
    All these values should have 32 bits, and I am only showing 16 bits here, but you see all you need to know how it works. The mask value sets all the bits in the result to zero except for the third bit, which is set to that of the indicators variable. Here, the result of the expression is non-zero because the third bit in indicators is 1. On the other hand, if the variable indicators contained the value 0xFF09 the result is different:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-bitwiseex0xff09.jpg
    Table: Bitwise Example using 0xFF09

    The result of the expression is now zero because the third bit of indicators is zero. As I said, you can use the | operator to set a particular bit on. For example, to set the third bit in
    indicators on, you can write the following:

    Java Code: Setting the 3rd bit on
    indicators = indicators | mask;
    You can see how this applies to the last value you had for indicators:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-bitwiseex3biton.jpg
    Table: Set the 3rd Bit On

    As you can see, the effect is just to switch the third bit of indicators on, leaving all the other bits unchanged. Of course, if the third bit was already on, it would stay on.
    You can also use the bitwise operators in the op= form. Setting the third bit in the variable indicators is usually written as:

    Java Code: Setting 3rd Bit
    indicators |= mask;
    Although there is nothing wrong with the original statement, the preceding one is just a bit more concise. To set a bit off you need to use the & operator again, with a mask that has 0 for the bit you want as 0, and 1 for all the others. To set the third bit of indicators off you could write:

    Java Code: Set the 3rd bit off, mask value 0x4
    indicators &= ~mask;
    The ~ operator provides a useful way of specifying a value with all bits 1 apart from one. The mask variable contains a value with the third bit as 1 and the other bits as 0. Applying the ~ operator to this flips each bit, so that the 0 bits are 1 and the 1 bit is zero. With indicators having the value 0xFF07, this would work as follows:

    Click image for larger version. 

Name:	D3-BitwiseEx3BitON.jpg 
Views:	5 
Size:	14.4 KB 
ID:	3748
    Table: Bitwise Example using 0xFF07

    [SIZE=4][B]Using the Exclusive OR Operator

    The ^ operator has the slightly surprising ability to interchange two values without moving either value somewhere else. The need for this turns up most frequently in tricky examination questions. Suppose you execute the following three statements with integer variables a and b:

    Java Code: Exclusive OR Operations
    a ^= b; 
    b ^= a; 
    a ^= b;
    The effect of these statements is to interchange the values of a and b, but remember this works only for integers. You can try this out with a couple of arbitrary values for a and b, 0b1101_0000_0000_1111 and 0b1010_1011_1010_1101, respectively—again, I am just showing 16 bits for each variable. The first statement changes a to a new value:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-bitwiseexclor.jpg
    Table: Bitwise Exclusive OR Example

    The next statement calculates a new value of b using the new value of a:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-bitwiseexclornewvala.jpg
    Table: Bitwise Exclusive OR using New Value of a

    So b now has a value that looks remarkably like the value that a started out with. Let's look at the last step, which calculates a new value for a using the new value of b:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-bitwiseexclornewvalb.jpg
    Table: Bitwise Exclusive OR Using New Value of b

    Lo and behold, the value of a is now the original value of b. When you get to do some graphics programming later in the book, you see that this application of the exclusive OR operator is quite useful.

    Using Assignment Operators

    The assignment operators set values and assign object references. The basic assignment operator (=) is by far the most often used operator. Everytime we put something like int = 0(assigning a value to a primitive) or Date now = new Date()(assigning an object reference to a variable) into an example,we use the basic assignment operator.

    Java provides a number of compound assignment operators (often called shortcut operators). The listing below is an example of one of the compound assignment operators.

    Java Code: Compound assignment operator
    int myInt = 2; 
    myInt *= 2; 
    // equivalent to myInt = myInt * 2; 
    System.out.println(myInt); // prints 4;
    Each of the compound operators applies the first operator within the compound operator and the value after the compound operator and then applies the assignment operator. In the previous example, the multiplication operator is applied to myInt with the value after the compound operator (in this case, doubling the value of myInt) and then sets myInt to the result. The compound assignment operators can lead to unexpected results. The listing below can lead to one not being clear as to the value of myInt:

    Java Code: Compound assignment problem
    int myInt = 2; 
    myInt *= (myInt = 4); 
    System.out.println(myInt);
    The last assignment before the print statement is myInt = 4,so you might think the answer must be 4. But we set myInt to 4 and then multiply it by itself, so you might think the answer must be 16. In fact, neither is correct. The code snippet prints 8. It might seem odd at first, but it makes sense once you understand how the JVM deals with a compound operator. When the JVM encounters the compound operator, it knows myInt equals 2. Until the entire operator is resolved, the value of myInt can't be changed. (This is the only case we know of where parentheses aren't processed first, by the way.) Consequently, the assignment within the line is ignored, but the value within the assignment is used. After all that, the result is 2 times 4, or 8. The table below shows all the assignment operators, including the compound operators:

    Tutorial:Review of Java Operators for the Java Certification Exam-d3-assignment-operators.jpg
    Table: Assignment Operators

    [B]Comparing and Sorting Objects

    As I indicated previously, comparing objects differs from comparing primitives. The comparison operators work for primitives, but they do not work for objects. Instead, Java requires the use of a number of different interfaces and methods to compare objects.

    [B]Implementing the equals Method

    The first comparison is to see whether one object is equal to another. The equality and inequality operators determine only whether two objects use the same object reference Therefore, two different objects, each with its own memory address, are never equal. To see whether two objects are equal, we have to compare objects that implement the equals method. The listing below shows this for the Person class:

    Java Code: Person class with equals method
    package com.acme.java.examples.comparing;
       public class Person { 
          String firstName; 
          String lastName;
    
          public Person (String firstName, String lastName) { 
             this.firstName = firstName;
             this.lastName = lastName;
          }
    
          public boolean equals(Person p) { 
             if (p == null) {
                return false;
             } if (p == this) {
                return true;
             }
    
          if (!(p instanceof Person)) {
             return false;
          } 
          if (p.lastName.equals(this.lastName)
              && p.firstName.equals(this.firstName)) { 
              return true;
          } else {
             return false;
         }
       }
    
       public int hashCode() { 
          int result = 17; 
          result *= firstName.hashCode() * 37; 
          result *= lastName.hashCode() * 37; 
          return result;
       }
    The standard practice for implementing the equals method is first to check for null, then check to see whether it's the same object, in which case they are certainly equal, next we check to make sure that, if we do have an object, it's the object we are comparing. If not, the comparison is always false. If other classes extend our Person class, such as a Worker object being equal to our Person object, then the equals method works for both. However, Worker might implement its own equals method to account for the school each Worker attends. Finally, you must check all the relevant fields within the class. If they are all equal, it must be the same person. The listing below shows a rewrite of CompareTest with the new Person object:

    Java Code: Checking people objects for equality
    package com.acme.java.examples.comparing; 
       public class CompareTest {
    }
    public static void main(String[] args) { 
       Person samSpade = new Person("Sam", "Spade"); 
       Person greatNoirDetective = new Person("Sam", "Spade"); 
       System.out.println(samSpade == greatNoirDetective); 
       System.out.println(samSpade.equals(greatNoirDetective));
    }
    CompareTest now prints “false” and then “true,” even though samSpade and greatNoirDetective are different references to different Person objects. That's because our equals method isn't comparing references but rather the relevant fields of the two objects.

    Commenting on Your Program

    Adding comments enhance the readability of your program. A program will often include multiple lines of comment in a program. For example, at the beginning of a method to explain what it does. One can use // at the beginning of a line to add comments or alternatively one can begin each line in a block of comments by putting /* at the beginning of the first comment line and */ at the end of the last comment line. Everything between the /* and the */ is ignored. There are also keywords that you can add to also enhance the documentation provided.

    Summary

    In this chapter, we have looked at the various Java operators available to do all sort of calculations of mathematics and logic including the precedence of operators, bitwise operators and its uses and using the equals and hashCode methods. In the next article we will delve into Java arrays.
    Last edited by Java Exam; 05-03-2012 at 12:16 AM.

Similar Threads

  1. Replies: 0
    Last Post: 05-02-2012, 12:10 AM
  2. Replies: 0
    Last Post: 05-01-2012, 10:24 PM
  3. Replies: 0
    Last Post: 04-11-2012, 06:06 PM
  4. Replies: 0
    Last Post: 04-06-2012, 09:24 PM
  5. Replies: 0
    Last Post: 03-26-2012, 02:11 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •