Operators

From Suhrid.net Wiki
Revision as of 03:42, 31 August 2011 by Suhridk (talk | contribs)
Jump to navigationJump to search

Compound Operators

  • +=, -=, *= and /=
  • Makes code compact
  • Operator precedence for compound assignments : The expression on the right side of the = will always be evaluated first!
int x = 2;

x *= 3 + 5;

//This is equivalent to x = x * (3 + 5) and NOT x = (x*2) + 5.

Relational Operators

  • Can be applied to ANY combination of integers, floats or chars.
  • int's can be compared to doubles
  • char's can be compared to int's
                int i = 4;
		double pi = 3.14;
		
		if( i > pi) {
			System.out.println("Greater than pi");
		}
		
		char c = 'C';
		
		if( c > 66) {
			System.out.println("C > B");
		}


Equality Operators

  • '==' and '!=' are used to test for equality.
  • Can't compare incompatible types.
  • For e.g can't compare an int and a boolean or a Thread and a String
  • Objects in the same hierarchy can be checked however.
Object o = new Object();
String s = new String("a");
Integer i = new Integer(42);
		
if(o == s) { //String IS-A object
 System.out.println("o==s");
} 
		
if (s == i) { // Compiler error
}
  • For enums, == is equivalent to equals(), because there's no way to create additional enum constants after the declaration.

instanceof

  • The instanceof (all small letters) is used for object variables only.