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

Monday, 16 January 2012

Modulus operator in java

Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):

x = n % d
 
n - dividend
d - divisor
 
The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:
  • If either operand is NaN, the result is NaN
    ...i.e. x=NaN, if n or d is NaN
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2

Saturday, 9 July 2011

Introduction to operators in java

Operators in java are similar to c++ and c.
Operators are actions that manipulate, combine or compare variables.
They fall into several categories as follows:
OperatorsSymbols
Assignment+= -= *= \= %=
Arithmetic+ - * / % (modulus)
++ (increment) -- (decrement)
String Concatenation+
Comparison or Relational Operators== , != , > , >= , < <=
Logical OR Boolean Comparison! & | ^ && || (&& are short circuit ops)
Bitwise Comparison~ & | ^ (xor) << >> >>>
Bitwise Assignment&= |= ^= (xor) <<= >>= >>>=
Conditional operator? (eg (expr1) ? expr2 : expr3 )
Object Creationnew (eg int a[] = new int[10];)
Class of Objectinstanceof
Casting of Type(var_type)

Note: Changes in data type are done explicitly using a cast operation. For examplea = (int) b; assumes a is of type int and b is of another type.

Number of Operands for Operators

Java operators can be classified as unary, binary, or ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its arguments.

Covering Various Operators in depth

Following are the operators in java:

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

&& vs & operator

Don't confuse &&, which is the short-circuit logical and, with &, which is the uncommon bitwise and. Altho the bitwise and can also be used with boolean operands, this is extremely rare and is almost always a programming error.

String concatenation operator in java

String concatenation operator is +.
eg. "ab" + "cd" = "abcd"

i.e.

String s1 = "ab";
String s2 = "cd";
String s3 = s1+s2;

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, 17 May 2011

Managing the subscript in java

In Java, the [] operator is predefined to perform bounds checking. Furthermore, there is no pointer arithmetic—you can't increment a to point to the next element in the array.Java always checks subscript legality to be sure the subscript is >= 0, and less than the number of elements in the array. If the subscript is outside this range, Java throws ArrayIndexOutOfBoundsException. This is far superior to the behaver of C and C++, which allow out of range references. Consequently, Java programs are far less susceptible to bugs and security flaws than C/C++ programs.

Thursday, 21 April 2011

Relational Operators in java

Java has six relational operators that compare two numbers and return a boolean value. The relational operators are <, >, <=, >=, ==, and !=.
x < y Less than True if x is less than y, otherwise false.
x > y Greater than True if x is greater than y, otherwise false.
x <= y Less than or equal to True if x is less than or equal to y, otherwise false.
x >= y Greater than or equal to True if x is greater than or equal to y, otherwise false.
x == y Equal True if x equals y, otherwise false.
x != y Not Equal True if x is not equal to y, otherwise false.
Here are some code snippets showing the relational operators.
boolean test1 = 1 < 2;  // True. One is less that two.
boolean test2 = 1 > 2; // False. One is not greater than two.
boolean test3 = 3.5 != 1; // True. One does not equal 3.5
boolean test4 = 17*3.5 >= 67.0 - 42; //True. 59.5 is greater than 5
boolean test5 = 9.8*54 <= 654; // True. 529.2 is less than 654
boolean test6 = 6*4 == 3*8; // True. 24 equals 24
boolean test7 = 6*4 <= 3*8; // True. 24 is less than or equal to 24
boolean test8 = 6*4 < 3*8; // False. 24 is not less than 24

This, however, is an unusual use of booleans. Almost all use of booleans in practice comes in conditional statements and loop tests. You've already seen several examples of this. Earlier you saw this

if (args.length > 0) {
System.out.println("Hello " + args[0]);
}

args.length > 0 is a boolean value. In other words it is either true or it is false. You could write

boolean test = args.length > 0;
if (test) {
System.out.println("Hello " + args[0]);
}

instead. However in simple situations like this the original approach is customary. Similarly the condition test in a while loop is a boolean. When you write while (i < args.length) the i < args.length is a boolean.




All relational operators are binary operators, and their operands are numeric expressions.
Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment operators.

Storing integral types in java


All the integer types in Java technology are internally stored in two's complement. In two's complement, positive numbers have their corresponding binary representation.
For negative numbers see - 2's complement of negative numbers in java

The shift operators- << , >> , >>>(3 operators) for int and long



The shift left operator in Java technology is "<<". There are two operators for doing the right shift - signed right shift (>>) and zero fill right shift (>>>). The left shift operator fills the right bits by zero. The effect of each left shift is multiplying the number by two. The example below illustrates this - int i = 13; // i is 00000000 00000000 00000000 0000 1101 
i = i << 2; // i is 00000000 00000000 00000000 0011 0100

 After this left shift, i becomes 52 which is same as multiplying i by 4 Zero fill shift right is represented by the symbol >>>. This operator fills the leftmost bits by zeros. So the result of applying the operator >>> is always positive. (In two's complement representation the leftmost bit is the sign bit. If sign bit is zero, the number is positive, negative otherwise.) The example below illustrates applying the operator >>> on a number.  
int b = 13; // 00000000 00000000 00000000 0000 1101 
b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011

So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains the effect of applying the operator >>> on a negative number.  
int b = -11; //11111111 11111111 11111111 1111 0101 
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101
So the result of applying zero fill right shift operator with operand two on -11 is 1073741821. Signed right shift operator (>>) fills the left most bit by the sign bit. The result of applying the signed shift bit has the same sign as the left operand. For positive numbers the signed right shift operator and the zero fill right shift operator both give the same results. For negative numbers, their results are different. The example below illustrates the signed right shift.  

int b = -11; // 11111111 11111111 11111111 1111 0101 

b = b >> 2; // 11111111 11111111 11111111 1111 1101 (2's complement of -3) // Here the sign bit 1 gets filled in the two most significant bits. 
The new value of b becomes -3.


1. How to generate a random number between 1 to x, x being a whole number greater than 1
Ans: double result = x * Math.random();

Important rules for the conditional operators - && and ||

Operator && returns true if both operands are true, false otherwise. Operator || returns false if both operands are false, true otherwise. The important thing to note about these operators is that they are short-circuited. This means that the left operand is evaluated before the right operator. If the result of the operation can be evaluated after computing the left operand, then the right side is not computed. In this respect these operators are different from their bit-wise counterparts - bit-wise and (&), and bit-wise or (|). The bit-wise operators are not short-circuited. This means both the operands of bit-wise operator are always evaluated independent of result of evaluations.

The equality operator


The equality operator (==) when applied to objects return true if two objects have same reference value, false otherwise. The example below illustrates this --

String str1 = "first string";
String str2 = new String("first string");
String str3 = "first string";
boolean test1 = (str1 == str2);
boolean test2 = (str1 == str3);
In the example above, test1 is set to false because str1 and str2 point to different references. As str1 and str3 point to the same reference, test2 gets set to true. When a string is initialized without using the new operator, and with an existing string, then the new string also points to the first string's location. So in the example above, str1 and str3 point to the same pool of memory and hence test2 gets set to true. The string str2 on the other hand is created using the new operator and hence points to a different block of memory. Hence test1 gets set to false.

Tuesday, 26 October 2010

Bitwise Operators - Uses

  • Efficient storage.
    • Status bits. Eg, Mouse event key mask.
    • Eg, representing Connect-Four board.
    • Packing or unpacking values into a single int/long.
      A common use of the bitwise operators (shifts with ands to extract values and ors to add values) is to work with multiple values that have been encoded in one int. Bit-fields are another way to do this. For example, let's say you have the following integer variables: age (range 0-127), gender (range 0-1), height (range 0-128). These can be packed and unpacked into/from one short (two-byte integer) like this (or many similar variations).
      //define the variables 

      int   age, gender, height;
      short packed_info;
      . . .
      // packing
      packed_info = (((age << 1) | gender) << 7) | height;
      . . .
      // unpacking
      height = packed_info & 0x7f;
      gender = (packed_info >>> 7) & 1;
      age = (packed_info >>> 8);

    • Setting flag bits
      Some library functions take an int that contains bits, each of which represents a true/false (boolean) value. This saves a lot of space and can be fast to process.

  • Efficient computation

    • On some (esp old) machines, shifting is faster than multiplying or dividing by powers of two.
      y = x << 3;        // Assigns 8*x to y.
      y = (x << 2) + x; // Assigns 5*x to y.

    • Flipping between on and off with xor

    • Sometimes xor is used to flip between 1 and 0.

      x = x ^ 1;      // Or the more cryptic x ^= 1;

      In a loop that will change x alternately between 0 and 1.

  • Problems

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!

Bitwise Operators

Java's bitwise operators operate on individual bits of integer (int and long) values. If an operand is shorter than an int, it is promoted to int before doing the operations.

It helps to know how integers are represented in binary. For example the decimal number 3 is represented as 11 in binary and the decimal number 5 is represented as 101 in binary.
Negative integers are store in two's complement form. For example, -4 is 1111 1111 1111 1111 1111 1111 1111 1100.

Bitwise operators can fall under 2 categories.>>,>>>,<< operators are called shift operators, which is covered in this post. Other operators are ~,&,| and ^ operators.
~ Not operator
^ Xor or Exclusive OR
| OR
& And operator
>> Right shift
>>> Unsigned right shift
<< left shift

Note that operands for Bitwise operators must be numeric datatypes(char, short, int, or long).

Examples - The bitwise operators

Operator Usage Example Result Reason
& or and Operator a & b 3 & 5 1 1 if both bits are 1.
| OR operator a | b 3 | 5 7 1 if either bit is 1.
^ or xor operator a ^ b 3 ^ 5 6 1 if both bits are different.
~ or not operator ~a ~3 4 Inverts the bits.
Left shift n << p 3 <<< 2 12 Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
Right shift n >> p 5 >> 2 1 Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
Unsigned right shift n >>> p -4 >>> 28 15 Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.