Pages

Monday, 15 February 2016

Operator and Expression


         If you want to learn the theorey from starting   click here



Expressions and Operators
 
Operators enable us to perform an evaluation or computation on a data object or objects.
Operators applied to variables and literals form expressions.
 
An expression can be thought of as a programmatic equation. Therefore, an expression is a sequence of one or more data objects (operands) and zero or more operators that produce a result.
 
An example of an expression follows:
x = y / 3;
In this expression, x and y are variables, 3 is a literal, and = and / are operators.

This expression states that the y variable is divided by 3 using the division
operator (/), and the result is stored in x using the assignment operator (=).

Here the expression is described from right to left.
Operator Precedence
 
Java expressions are typically evaluated from left to right, there still are many times when the result of an expression would be indeterminate without other rules.
 
The following expression illustrates the problem:
x = 2 * 6 + 16 / 4
 
 
By using the left-to-right evaluation of the expression, the multiplication operation 2 * 6 is carried out first, which leaves a result of 12. The addition operation 12 + 16 is then performed, which gives a result of 28. The division operation 28 / 4 is then performed, which gives a result of 7. Finally, the assignment operation x = 7 is handled, in which the number 7 is assigned to the variable x.

But--it's wrong! The problem is that using a simple left-to-right evaluation of expressions can yield inconsistent results, depending on the order of the operators.

The solution to this problem lies in operator precedence, which determines the order in which operators are evaluated. Every Java operator has an associated precedence.

Following is a list of all the Java operators from highest to lowest precedence.

In this list of operators, all the operators in a particular row have equal precedence.

The precedence level of each row decreases from top to bottom. This means that the [] operator has a higher precedence than the * operator, but the same precedence as the () operator.
 
 
.[]() 
++-!~
*/% 
+-  
<<>>>>> 
<><=>=
=!=  
&   
^   
&&   
||   
?:   
=   
 
Evaluation of expressions still moves from left to right, but only when dealing with operators that have the same precedence.
 
Otherwise, operators with a higher precedence are evaluated before operators with a lower precedence.
 
Knowing this, take another look at the sample equation:
x = 2 * 6 + 16 / 4
 
Before using the left-to-right evaluation of the expression, first look to see whether any of the operators have differing precedence.
 
Here the multiplication (*) and division (/) operators both have the highest precedence, followed by the addition operator (+), and then the assignment operator (=).

Because the multiplication and division operators share the same precedence, evaluate
them from left to right. Doing this, we first perform the multiplication operation 2 * 6
with the result of 12. Then we perform the division operation 16 / 4, which results in 4.
 
After performing these two operations, the expression looks like this:
x = 12 + 4;
 
Because the addition operator has a higher precedence than the assignment operator, we perform the addition operation 12 + 4 next, resulting in 16. Finally, the assignment operation x = 16 is processed, resulting in the number 16 being assigned to the variable x.
 
As we can see, evaluating the expression using operator precedence yields a completely different result.
 
Just to get the point across, take a look at another expression that uses parentheses for grouping purposes:
x = 2 * (11 - 7);
 
Without the grouping parentheses, we would perform the multiplication operation first and then the subtraction operation. However, referring back to the precedence list, the () operator comes before all other operators. So the subtraction operation 11 - 7 is performed first, yielding 4 and the following expression:
x = 2 * 4;
 
The rest of the expression is easily resolved with a multiplication operation and an assignment operation to yield a result of 8 in the variable x.

Integer Operators
 
There are three types of operations that can be performed on integers:
1. unary,
2. binary,
3. And relational.
 
Unary operators act on only single integer numbers,

Binary operators act on pairs of integer numbers.

Both unary and binary integer operators typically return integer results.

Relational operators, act on two integer numbers but return a Boolean result rather than an integer.

Unary and binary integer operators typically return an int type. For all operations involving the types byte, short, and int, the result is always an int.
The only exception to this rule is when one of the operands is a long, in which case the result of the operation is also of type long.
 
 
Unary Integer Operators
Unary integer operators act on a single integer. Lists of the unary integer operators.
 
The unary integer operators.
 
DescriptionOperator
Increment++
Decrement--
Negation-
Bitwise complement~
 
 
The increment and decrement operators (++ and --) increase and decrease integer ariables by 1.

These operators can be used in either prefix or postfix form. A prefix operator takes effect before the evaluation of the expression it is in; a postfix operator takes effect after the expression has been evaluated.

Prefix unary operators are placed immediately before the variable; postfix unary operators are placed immediately following the variable. Following are examples of each type of operator:
y = ++x;
z = x--;
 
In the first example, x is prefix incremented, which means that it is incremented before being assigned to y.
In the second example, x is postfix decremented, which means that it is decremented after being assigned to z. Here z is assigned the value of x before x is decremented.
The IncDec program, which uses both types of operators.
 
The IncDec class.
 
class IncDec
{
public static void main (String args[])
{
int x = 8, y = 13;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("++x = " + ++x);
System.out.println("y++ = " + y++);
System.out.println("x = " + x);
System.out.println("y = " + y);
}

}
 
The IncDec program produces the following results:
 
x = 8
y = 13
++x = 9
y++ = 13
x = 9
y = 14
Output
 
The negation unary integer operator (-) is used to change the sign of an integer value.
x = 8;
y = -x;
 
In this example, x is assigned the literal value 8 and then is negated and assigned to y.
The resulting value of y is -8.
 
The Negation class.
 
class Negation
{
public static void main (String args[])
{
int x = 8;
System.out.println("x = " + x);
int y = -x;
System.out.println("y = " + y);
}

}
Output
 
The bitwise complement operator (~), which performs a bitwise negation of an integer value.
Bitwise negation means that each bit in the number is toggled. In other words, all the binary 0s become 1s and all the binary 1s become 0s.
 
Example:
x = 8;
y = ~x;
 
In this example, x is assigned the literal value 8 again, but it is bitwise complemented before being assigned to y.

Well, without getting into the details of how integers are stored in memory, it means that all the bits of the variable x are flipped, yielding a decimal result of -9. This result has to do with the fact that negative numbers are stored in memory using a method known as two's complement.

NOTE: Integer numbers are stored in memory as a series of binary bits that can each have a value of 0 or 1. A number is considered negative if the highest-order bit in the number is set to 1. Because a bitwise complement flips all the bits in a number--including the high-order bit--the sign of a number is reversed.
 
 
The Bitwise Complement class.
class BitwiseComplement
{
public static void main (String args[])
{
int x = 8;
System.out.println("x = " + x);
int y = ~x;
System.out.println("y = " + y);
}

}
Output
 
 
Binary Integer Operators
Binary integer operators act on pairs of integers. Lists of the binary integer operators.
 
The binary integer operators.
 
DescriptionOperator
Addition+
Subtraction-
Multiplication*
Division/
Modulus%
Bitwise AND&
Bitwise OR|
Bitwise XOR^
Left-shift<<
Right-shift>>
Zero-fill-right-shift>>>
 
 
The Arithmetic program, which shows how the basic binary integer arithmetic operators work.
 
 
The Arithmetic class.
 
class Arithmetic
{
public static void main (String args[])
{
int x = 17, y = 5;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x + y = " + (x + y));
System.out.println("x - y = " + (x - y));
System.out.println("x * y = " + (x * y));
System.out.println("x / y = " + (x / y));
System.out.println("x % y = " + (x % y));
}

}
 
The results of running the Arithmetic program follow:
 
x = 17
y = 5
x + y = 22
x - y = 12
x * y = 85
x / y = 3
x % y = 2
Output
 
The bitwise AND, OR, and XOR operators (&, |, and ^) all act on the individual bits of an integer. These operators are sometimes useful when an integer is being used as a bit field.
 
 
The Bitwise class.
 
class Bitwise
{
public static void main (String args[])
{
int x = 5, y = 6;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x & y = " + (x & y));
System.out.println("x | y = " + (x | y));
System.out.println("x ^ y = " + (x ^ y));
}

}
 
The output of running Bitwise follows:
 
x = 5
y = 6
x & y = 4
x | y = 7
x ^ y = 3
 
In Bitwise, the variables x and y are set to 5 and 6, which correspond to the binary numbers 0101 and 0110.
 
The bitwise AND operation compares each bit of each number to see whether they are the same. It then sets the resulting bit to 1 if both bits being compared are 1; it sets the resulting bit to 0 otherwise. The result of the bitwise AND operation on these two numbers is 0100 in binary, or decimal 4.
 
The bitwise OR operator sets the resulting bit to 1 if either of the bits being compared is 1. For these numbers, the result is 0111 binary, or 7 decimal.
 
Finally, the bitwise XOR operator sets resulting bits to 1 if exactly one of the bits being compared is 1 and 0 otherwise. For these numbers, the result is 0011 binary, or 3 decimal.
The left-shift, right-shift, and zero-fill-right-shift operators (<<, >>, and >>>) shift the individual bits of an integer by a specified integer amount.
 
Following are some examples of how these operators are used:
 
x << 3;
y >> 7;
z >>> 2;
 
In the first example, the individual bits of the integer variable x are shifted to the left three places.
In the second example, the bits of y are shifted to the right seven places.
Finally, the third example shows z being shifted to the right two places, with zeros shifted into the two leftmost places.
The Shift class.
 
class Shift
{
public static void main (String args[])
{
int x = 7;
System.out.println("x = " + x);
System.out.println("x >> 2 = " + (x >> 2));
System.out.println("x << 1 = " + (x << 1));
System.out.println("x >>> 1 = " + (x >>> 1));
}

}
 
The output of Shift follows:
 
x = 7
x >> 2 = 1
x << 1 = 14
x >>> 1 = 3
Output
 
The number being shifted in this case is the decimal 7, which is represented in binary as 0111. The first right-shift operation shifts the bits two places to the right, resulting in the binary number 0001, or decimal 1.

The next operation, a left-shift, shifts the bits one place to the left, resulting in the binary number 1110, or decimal 14.

The last operation is a zero-fill-right-shift, which shifts the bits one place to the right, resulting in the binary number 0011, or decimal 3.

Relational Integer Operators
 
The last group of integer operators is the relational operators, which all operate on
integers but return a type boolean. Lists of the relational integer operators.
 
The relational integer operators.
 
Description
Operator
Less-than<
Greater-than>
Less-than-or-equal-to<=
Greater-than-or-equal-to>=
Equal-to==
Not-equal-to!=
 
These operators all perform comparisons between integers.
 
The Relational class
 
class Relational
{
public static void main (String args[])

{
int x = 7, y = 11, z = 11;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
System.out.println("x < y = " + (x < y));
System.out.println("x > z = " + (x > z));
System.out.println("y <= z = " + (y <= z));
System.out.println("x >= y = " + (x >= y));
System.out.println("y == z = " + (y == z));
System.out.println("x != y = " + (x != z));
}

}
 
The output of running Relational follows:
 
x= 7
y = 11
z = 11
x < y = true
x > z = false
y <= z = true
x >= y = false
y == z = true
x != y = true
Output

Floating point Operators
 
There are three types of operations that can be performed on floating-point numbers:
1. unary,
2. binary,
3. and relational
 
 
Unary operators act only on single floating-point numbers,

binary operators act on pairs of floating-point numbers.

Both unary and binary floating-point operators return floating-point results.

Relational operators, act on two floating-point numbers but return a boolean result.

Unary and binary floating-point operators return a float type if both operands are of type float. If one or both of the operands are of type double, however, the result of the operation is of type double.
 
 
Unary Floating-Point Operators
The unary floating point operators act on a single floating-point number. Lists of the unary floating-point operators.
 
The unary floating-point operators.
DescriptionOperator
Increment++
Decrement--
 
The only two unary floating-point operators are the increment and decrement operators. These two operators respectively add and subtract 1.0 from their floating-point operand.
 
 
Binary Floating-Point Operators
The binary floating-point operators act on a pair of floating-point numbers. Lists of the binary floating-point operators.
 
The binary floating-point operators.
DescriptionOperator
Addition+
Subtraction-
Multiplication*
Division/
Modulus%
 
The binary floating-point operators consist of the four traditional binary operations (+, -, *, /), along with the modulus operator (%).
 
 
The FloatMath class.
 
class FloatMath
{
public static void main (String args[])
{
float x = 23.5F, y = 7.3F;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x + y = " + (x + y));
System.out.println("x - y = " + (x - y));
System.out.println("x * y = " + (x * y));
System.out.println("x / y = " + (x / y));
System.out.println("x % y = " + (x % y));
}

}
 
The output of FloatMath follows:
 
x = 23.5
y = 7.3
x + y = 30.8
x - y = 16.2
x * y = 171.55
x / y = 3.21918
x % y = 1.6
Output


Relational Floating-Point Operators
 
The relational floating-point operators compare two floating-point operands, leaving a boolean result.
 
Boolean Operators
Boolean operators act on boolean types and return a boolean result.
 
 
The boolean operators
 
DescriptionOperator
Evaluation AND&
Evaluation OR|
Evaluation XOR^
Logical AND&&
Logical OR||
Negation!
Equal-to==
Not-equal-to!=
Conditional?:
 
The evaluation operators (&, |, and ^) evaluate both sides of an expression before determining the result.
 
The following code shows how the evaluation AND operator is necessary for the complete evaluation of an expression:
 
while ((++x < 10) && (++y < 15)) {
System.out.println(x);
System.out.println(y);


}
 
The three boolean operators--negation, equal-to, and not-equal-to (!, ==, and !=)
The negation operator toggles the value of a boolean from false to true or from true to false, depending on the original value.
The equal-to operator simply determines whether two boolean values are equal (both true or both false).

Similarly, the not-equal-to operator determines whether two boolean operands are unequal.

The conditional boolean operator (? :) is the most unique of the boolean operators This operator also is known as the ternary operator because it takes three items: a condition and two expressions.

The syntax for the conditional operator follows:

Condition ? Expression1 : Expression2

The Condition, which itself is a boolean, is first evaluated to determine whether it is true or false. If Condition evaluates to a true result, Expression1 is evaluated. If Condition ends up being false, Expression2 is evaluated.
 
 
The Conditional class
 
class Conditional
{
public static void main (String args[])
{
int x = 0;
boolean isEven = false;
System.out.println("x = " + x);
x = isEven ? 4 : 7;
System.out.println("x = " + x);
}

}
 
The results of the Conditional program follow:
x = 0
x = 7
Output
 
String Operator
 
There is only one string operator: the concatenation operator (+). The concatenation
operator for strings works very similarly to the addition operator for numbers--it adds
strings together.
 
 
The Concatenation class
 
class Concatenation
{
public static void main (String args[])
{
String firstHalf = "What " + "did ";
String secondHalf = "you " + "say?";
System.out.println(firstHalf + secondHalf);
}

}
 
The output of Concatenation follows:
What did you say?
Output
 
In the Concatenation program, literal strings are concatenated to make assignments to
the two string variables, firstHalf and secondHalf, at time of creation. The two string
variables are then concatenated within the call to the println() method.

Assignment Operators
 
Assignment operators actually work with all the fundamental data types.
 
The assignment operators
 
Description
Operator
Simple=
Addition+=
Subtraction-=
Multiplication*=
Division/=
Modulus%=
AND&=
OR|=
XOR^=
 
Examples:
x += 6;
x *= (y - 3);
 
In the first example, x and 6 are added and the result stored in x.
In the second example, 3 is subtracted from y and the result is multiplied by x.
The final result is then stored in x.

Arithmetic assignment operations
 
  1. Combine arithmetic and assignment into a single operation to save coding time
  2. All five basic arithmetic operations have a corresponding arithmetic assignment operator .
 
Operator
Operation
+=Addition assignment
-=Subtraction assignment
*=Multiplication assignment
/=Division assignment
%=Modulo (remainder) assignment
 
Example:
This program reads a percentage value from the user (such as 5.5) and converts to the correct decimal equivalent (such as 0.055) by using the division assignment operator.
 
import java.util.*;
import java.io.*;

public class AppStr
{
public static void main(String[] args)
{

// Variable for holding a percentage entered by the user // Prompt for and read the percentage System.out.print("Enter a percentage in n.nn format: ");
double percent;
Scanner Keyboard = new Scanner(System.in);

percent = Keyboard.nextDouble();
//percent = Keyboard.readDouble();
// Convert it to its decimal equivalent and display the result
percent /= 100;
System.out.println("The decimal equivalent is " + percent);
}
}
Output



Conversions
 
Conversion is performed automatically when mixed numeric types appear within an expression.

Variables and constants are not altered, but their values are copied to intermediate areas of larger size or precision to prevent possible data loss during the calculation. This is known as a "widening" conversion.
 
The order of conversion (from narrowest to widest) is as follows. Memorize this table!
 
 
The data type resulting from an expression is that of the largest or most precise variable or constant appearing in the expression but is never smaller than int.
 
Example:
This program to convert a fahrenheit temperature to celsius will NOT compile.
 
import
java.util.*;
import java.io.*;
public class Conversion
{
public static void main(String[] args)
{

// Variables for holding fahrenheit and celsius temperatures

float tempC;

// Prompt for and read the fahrenheit temperature

System.out.print("Enter the fahrenheit temperature (nn.n): ");
Scanner Keyboard=new Scanner(System.in);
double tempF;
tempF= Keyboard.nextDouble();

// Convert to celsius and display the result

tempC = 5 * (tempF - 32) / 9;
System.out.println("Celsius equivalent is " + tempC);

}
}
 
Note:
To fix the compile error in this code, tempC must be double or tempF must be float .
 

Casts
 
1. Are a programmer's way of telling the compiler to ignore possible loss of data or
precision that might result from a conversion?
 
2. Should be used with caution. Data loss is not to be taken lightly.
 
3. The general syntax is
identifier = (data-type) expression;
 
Example:
This is a corrected version of the previous program that uses a cast to prevent the compile error.
 
import java.util.*;
import java.io.*;
public class Application
{
public static void main(String[] args)
{

// Variables for holding fahrenheit and celsius temperatures

float tempC;

// Prompt for and read the fahrenheit temperature

System.out.print("Enter the fahrenheit temperature (nn.n): ");
Scanner Keyboard=new Scanner(System.in);
double tempF;
tempF=Keyboard.nextDouble();

// Convert to celsius and display the result

tempC = (float) (5 * (tempF - 32) / 9);
System.out.println("Celsius equivalent is " + tempC);
}
}
Output
 
Some thing on arithmetic expressions
Arithmetic expressions can be large and complex with several variables, constants, and operators. The order in which operations are performed is the same as in mathematics (multiplication and division first, then addition and subtraction, working from left to right).

To avoid confusion, good programmers keep their expressions as simple as possible and use parenthesis for clarity.


Boolean expressions and operations
 
Boolean expressions
1. Always result in a boolean value (either true or false)
 
2. Are used to resolve logic questions, such as determining if two variables have the same     value?
 
3. May contain several different operators?
 
 
Comparison operators
1. Used to compare the values of two variables or constants
 
2. Require that the two operands be either both numeric (including char) or both      boolean. A numeric value cannot be compared to a boolean value.
 
3. Frequently appear in if, for, while, and do-while statements (to be covered later)
 
Operator
Operation
<Less than
<=Less than or equal
>Greater than
>=Greater than or equal
==Equal
!=Not equal
 
Example:
This program reads two numeric values from the user and displays the result of several comparisons involving the two numbers.
 
import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Variables for holding two numeric values entered by the user

int x;
double y;

// Prompt for and read the two numeric values

System.out.print("First number (integer): ");
Scanner Keyboard=new Scanner(System.in);
int x;
x=Keyboard.nextInt(();
System.out.print("Second number (floating-point): ");
Scanner Keyboard=new Scanner(System.in);
double y;
y=Keyboard.nextDouble();

// Display information comparing the two values

System.out.println(" " + x + " < " + y + " is " + (x "<" y));
System.out.println(" " + x + " <= " + y + " is " + (x <= y));
System.out.println(" " + x + " > " + y + " is " + (x > y));
System.out.println(" " + x + " >= " + y + " is " + (x >= y));
System.out.println(" " + x + " == " + y + " is " + (x == y));
System.out.println(" " + x + " != " + y + " is " + (x != y));
}
}
Output


Logical operators
 
1. Combine the results of two Boolean expressions into a single boolean value
2. Provide for complex logic. The following table shows the operators and how they can be
 used to combine the results of two Boolean expressions X and Y:
 
Operator
Operation
Resulting value true if...
X and Y always evaluated?
&ANDX and Y are both trueYes
|OReither X or Y is trueYes
^XOR (exclusive OR)X and Y have different valuesYes
&&Conditional ANDX and Y are both trueNo
||Conditional OReither X or Y is trueNo\
 
 
The conditional AND ( && ) and OR ( || ) are sometimes called "short-circuit" operators because the second operand is not always evaluated depending on the value of the first operand. If the first operand is false, the result of an AND will always be false regardless of the value of the second operand. If the first operand is true, the result of an OR will always be true regardless of the value of the second operand.
 
Example:
The following program uses two values entered by the user to determine if a customer is entitled to free shipping. A customer receives free shipping if their order amount is greater than or equal to 100 and they are a preferred customer.
 
import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Variables for holding order amount and valued customer data to be
// entered by the user


// Variables for holding information about free shipping

boolean isFree;

// Prompt for and read order amount and valued customer data

System.out.print("Order amount (floating-point): ");
Scanner Keyboard= new Scanner(System.in);
double amount;
amount =Keyboard.nextDouble();
System.out.print("Valued customer? (Y)es or (N)o: ");
Char valuedCust;

valuedCust = Keyboard.nextChar();

// Determine and display information about free shipping.
// Shipping is free if the order amount is greater than or equal $100
// AND the customer is a valued customer.

isFree = (amount >= 100 && (valuedCust == 'Y' || valuedCust == 'y'));
System.out.println(" Free shipping? " + isFree);
}
}
Output
 
 
Certain logical operators can be combined with assignment
 
1. The operators are &= (AND equals), |= (OR equals), and ^= (XOR equals)
2. The left operand must be boolean
 
 
Example:
The following program reads a boolean value from the user and displays its opposite value.
 
public class AppCer
{
public static void main(String[] args)
{

// Variable for holding a boolean value entered by the user

boolean value;

// Prompt for and read the boolean value

System.out.print("Enter a boolean value (true or false): ");
value = Keyboard.readBoolean();

// Determine the opposite value. If the value is false, XOR with
// true results in true. If the value is true, XOR with true results
// in false.

value ^= true;

// Display the new value of the value.

System.out.println(" The opposite value is " + value);
}
}
***try this yourself



Bitwise operations
 
Bitwise operations act upon individual bits within integer data.
They are used to perform the logical operations AND, OR, and XOR (eXclusive OR), complementing (reversing all bits), and shifting (sliding bits to the left or right).
 
 
Logical bitwise operations
 
1. Use the standard boolean operators (&, |, and ^) to act upon two integer values. The     short-circuit boolean operators (&& and ||) are not used for bitwise operations and will     result in a compile error if attempted.
 
2. Produce an integer result (of size int or larger) that is the logical AND, OR, or XOR of two     operands.
 
The rules for these operations are as follows:
 
Operation
Rule
&If both corresponding operand bits are "on" the result bit is "on"
|If either corresponding operand bit is "on" the result bit is "on"
^If corresponding operand bits are different the result bit is "on"

The complement operator
 
1. Is unary (has a single operand)?
2. Uses the ~ operator to "flip" (reverse) the bits within an integer value. If a bit is "on" it is     turned "off". If a bit is "off" it is turned "on".
 
For example,
if
byte a = 17; // Binary value: 0001 0001 Hex value: 11
byte b;
after executing the statement
b = (byte) ~a;
variable b will have a value of -18 (because 0001 0001 reverses to 1110 1110). Once again, the cast is needed in order to store the int value that results from the operation.
 
Example:
The following program can be run to test complement operations.
 
import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Variable to be read from the user


// Prompt for and read an integer value

System.out.print("Integer: ");
Scanner Keyboard=new Scanner(System.in);
int number;
number=Keyboard.nextInt();


// Display the result of complementing the number

System.out.println(" ~" + number + " = " + ~number);
}
}
Output


Previous Page                                Scroll Up                         Next Page

                                   



     

No comments:

Post a Comment