Showing posts with label operators. Show all posts
Showing posts with label operators. Show all posts

Monday, 23 May 2011

Conditional operators in java

The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)

int x = 10, y = 12, z = 0;
z = x > y ? x : y;
//As x>y is false, z=y

Compound operators in java

The compound operators perform shortcuts in common programming operations. Java has eleven compound assignment operators.
Syntax:

argument1 operator = argument2.

The above statement is the same as, argument1 = argument1 operator argument2. An example program is shown below that demonstrates the different Compound operators in java.

int x = 0, y = 5;
x += 3; //x = 3 now
y *= x; // y = 5*x = 15

Logical or Conditional Operators in java

Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logical operator must be a boolean data type, and the result is always a boolean data type.
Symbol Name
AND &&
OR ||
NOT !
An example program is shown below that demonstrates the different Logical operators in java.
Example of &&
boolean b;
b = 3 > 2 && 5 < 6; // b is true
b = 2 > 3 && 5 < 6; // b is now false


Example of ||


boolean b;
b = 3 > 2 || 5 < 6; // b is true
b = 2 > 3 || 5 < 6; // b is still true

Example of !

boolean b;
b = !(3 > 2); // b is false
b = !(2 > 3); // b is true

Also there are bitwise logical operators also, please have a look.
Also see important rule for conditional operators - || and &&

Arithmetic operators in java

Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below that demonstrates the different arithmetic operators in java.

The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed.

String message = 100 + “Messages”; //”100 Messages”

The assignment operators in java

The java assignment operator statement has the following syntax:

<variable> = <expression>

If the value already exists in the variable it is overwritten by the assignment operator (=).

j = 10; // j gets the value 10.
j = 5; // j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.

// Multiple Assignments
k = j = 10; // (k = (j = 10))


But in case of reference, just a shallow copy is made:


SomeClass obj1 = new SomeClass();
SomeClass obj2 = new SomeClass();
obj2 = obj1;


obj2 and obj1 are 2 references pointing to the same object, which was initialized in 1st statement by obj1.

Sunday, 22 May 2011

The instanceof operator in java

The instanceof operator is a binary operator that determines whether an object reference (the left operand) is an instance of the class, interface, or array type specified by the right operand. The instanceof operator cannot be used with primitive types (this results in a compilation error).

The instanceof operator returns a boolean value of true if the left operand references a non-null object of class C (or array of type T), so that at least one of the following conditions holds.
  • The right operand is a class name C' and C is a subclass of C'.
  • The right operand is an interface name I, and C implements I.
  • The right operand is an array of type T', the left operand is an array of type T, and T is a subclass or subinterface of T' or equal to T'.
The instanceof operator returns false if none of the above conditions are met or if the left operand is null.

String s = "abcd";
Vector v = new Vector();
v.add(s);
Object o = v.elementAt(0);
System.out.println(s instanceof String); // 1.true
System.out.println(s instanceof Object); //2.true
//because String is subclass of Object class
System.out.println(o instanceof String); //3.true
System.out.println(o instanceof Object); //4.true
System.out.println(o instanceof Vector); //5.false


The third output line displays a value of true even though o is declared to be of type Object. How is this so? That's because the object assigned to o is the String object that was added to Vector v.
The fourth and fifth output lines result from the fact that a String object is an Object object but not a Vector object.

Tuesday, 26 October 2010

Operator Precedence

Precedence determines order of evaluation

Mathematical tradition, which programming languages generally try to match, dictates that some operations are done before others (for example, multiplication and division are done before addition and subtraction).

a+b*c is the same as a+(b*c), not (a+b)*c.

Ever operator has a precedence (a number) associated with it. The precedence determines which operations will be performed first. Multiplication has higher precedence than addition, as illustrated in the previous example..

Equal precedence operations generally performed left-to-right

In addition to the precedence of each operator, the compiler also knows whether equal-precedence operators should be performed left-to-right (almost all) or right-to-left (basically only assignment).

Parentheses can be used to control the order of evaluation

If you have any doubt about the order of evaluation, or have a potentially confusing expression, use parentheses. Remember that one of your goals should be to make your programs as readable as possible. Use parentheses when it makes an expression easier to read, not must when they are absolutely required. Few programmers know the precedence of all operators, so it's common for extra parentheses to be used.

Unary (one operand) versus binary (two operand) operators

Unary operators have only one operand, for example, in

   a = -b;

The "-" operator is the unary (one operand) operator which changes the sign of its operand.

   a = b - c

The "-" operator is a binary (two operand) operator which subtracts c from b.

Most unary operators are performed before binary operators (exceptions "." (qualification), "[]" (subscription), and "()" (method call).

Example - Parentheses


When you can work out the precedence, it's often useful to use parentheses to figure out the order of evaluation. For example, let's say you're evaluating the following expression.

 1 + 2 - 3 * 4 / 5

Addition and subtraction are equal in precedence and lower than multiplication and division, which are equal. Form the parenthesized form and work out the values in steps.


  1. 1 + 2 - 3 * 4 / 5
  2. = (1 + 2) - ((3 * 4) / 5)
  3. = 3 - (12/5)
  4. = 3 - 2 The result of the integer division, 12/5, is 2 .
  5. = 1

Precedence table


This table gives the precedence of all operators. You may not be familiar with all operators, but take the advice on the right side and only learn a few precedences.

Operator Precedence

. [] (args) post ++ --
! ~ unary + - pre ++ --
(type) new
* / %
+ -
<< >> >>>
< <= > >= instanceof
== !=
&
^
|
&&
||
?:
= += -= etc

Remember only

  1. unary operators
  2. * / %
  3. + -
  4. comparisons
  5. && ||
  6. = assignments
Use () for all others

Alternative notation - Dataflow diagram


Let's look at the expression x = a+b-c*d/e, which can be parenthesized as x = ((a+b) - ((c*d)/e)). Instead of parentheses, we can draw a diagram.

dataflow-tree
This dataflow diagram shows another way to think about expression evaluation.

Boxes represent values in memory, ovals represent operations, and arrows show the direction of data flow. The assignment operator ("=") is treated as an operator with low precedence by the compiler, but from a dataflow point of view it only moves data so it's represented as an arrow, not an operation.

Dataflow diagrams show which operations must necessarily be performed before others, but doesn't show which are actually performed first. Java performs most operations left-to-right, so the addition would, in principle, be performed before the multiplication. I believe reordering of operations that can have no side effects is allowed, however.

Alternative notation - Postfix - RPN


Postfix. Altho it's not directly relevant to learning Java, there are other systems for writing expressions that don't need parentheses or precedence. Normal mathematical notation is called infix notation because the operators occur in between the operands. A common alternative is called postfix notation where the operator is written after its two operands.

Example. For example, a+b would be written as ab+ , and x = a+b-c*d/e would be written as xab+cd*e/-=.

RPN. This is often called Reverse Polish Notation in honor of the Polish mathematician Jan Lukasiewicz.

Postfix notation is used in the following, among others.


  • Hewlett-Packard makes RPN calculators.
  • The Postscript printer control language is postfix.
  • The Forth programming language is RPN.
  • Java source code is translated into postfix notation!