Operators

From Suhrid.net Wiki
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.
  • The first operand must be an object instance and the second operator a class name.
  • Instanceof can be used to compare operands which are in the same class hierarchy, However this restriction does not apply to interfaces !
class GrandFather {
}

class Father extends GrandFather {
}

class Son extends Father {
}

public class InOf {

	public static void main(String[] args) {
		Father f = new Father();
		GrandFather gf = new GrandFather();
		Son s = new Son();
		
		if (f instanceof GrandFather) { //OK
		}
		
		if (f instanceof Son) { //OK
		}
		
		if (f instanceof Thread) { //ILLEGAL COMPARE : NOT OK
		}

                if (f instanceof Runnable) { //OK TO COMPARE
                }
		
	}
}
  • If a class's superclass implements an interface then the class will pass the instanceof test for the interface
interface Person {
}

class GrandFather implements Person {
}

class Father extends GrandFather {
}

class Son extends Father {
}

public class InOf {

	public static void main(String[] args) {
		
		Son s = new Son();
		
		if (s instanceof Person) {
			System.out.println("Son is a Person"); //Will print Son is a Person
		}
		
	}

}
  • IT IS LEGAL to use null reference in an instanceof check. It will always return false.
  • Can also be used for arrays
Integer[] ia = new Integer[20];
		
if(ia instanceof Number[]) {
   System.out.println("Integer[] IS-A Number[]"); //Prints this 
}

Arithmetic Operators

  • +, -, *, /, % are the arithmetic operators.
  • *, /, % have a higher precedence than the + and - operators.

String concatenation operator

  • '+' is the only "overloaded" operator in java and can be used to concatenate two strings together.
  • WATCH OUT : When integers are concatenated with Strings :
  • Evaluation runs from left to right
  • If both operands are integers, then addition will take place.
  • If one operand is a string, concatenation will happen.
System.out.println(1 + 2 + " abc"); // 3 abc
System.out.println(1 + " abc " + 2); // 1 abc 2
System.out.println(1 + 2 + " abc " + 3); // 3 abc 3
System.out.println(1 + 2 + " abc " + 3 + 4); // 3 abc 34

Conditional Operator

  • Is a ternary operator (three operands)
  • Syntax:
  • x = (boolean expression) ? value to assign if bool expr is true : value to assign if bool expr is false.
  • value should match with type of x
  int c  = (new Random().nextInt(10) > 5) ? 1 : 0;

Logical Operator

  • Six logical operators - &, |, ^, !, &&, !!
  • & , |, ^ are also bitwise operators - they compare variables bit by bit and return a value whose bits have been set according to the comparison made.
int i = 3;
int j = 5;

int k = i & j; //k = 1;

Short Circuit Logical Operators

  • Short circuit && evaluates the first operand and if it resolves to false, it skips evaluating the remaining operands because the end result will be false.
  • Short circuit || evaluate the first operand and if it is true, it wont evaluate the rest of the expressions because the end result will be true.
public static void main(String[] args) {
		if(expr1() && expr2() && expr3()) {
			System.out.println("True");
		} else {
			System.out.println("False");
		}
		
		System.out.println("------------------------------");
		
		if(expr1() || expr2() || expr3()) {
			System.out.println("True");
		} else {
			System.out.println("Flase");
		}
	}
	
	private static boolean expr1() {
		System.out.println("expr1");
		return false;
	}
	
	private static boolean expr2() {
		System.out.println("expr2");
		return true;
	}
	
	private static boolean expr3() {
		System.out.println("expr3");
		return true;
	}

/* OUTPUT :
expr1
False
------------------------------
expr1
expr2
True
/*

Non Short-Circuit Logical Operators

  • When & and | are used, they always evaluate all the operands - nothing is skipped.
public class SCircuit {

	public static void main(String[] args) {
		if(expr1() & expr2() & expr3()) {
			System.out.println("True");
		} else {
			System.out.println("False");
		}
		
		System.out.println("------------------------------");
		
		if(expr1() | expr2() | expr3()) {
			System.out.println("True");
		} else {
			System.out.println("False");
		}
	}
	
	private static boolean expr1() {
		System.out.println("expr1");
		return false;
	}
	
	private static boolean expr2() {
		System.out.println("expr2");
		return true;
	}
	
	private static boolean expr3() {
		System.out.println("expr3");
		return true;
	}

}

/*
OUTPUT:
expr1
expr2
expr3
False
------------------------------
expr1
expr2
expr3
True
*/