-->

Sunday, May 4, 2014

Operator Precedence and Associativity to Evaluate Expression: JAVA

Operator precedence determines the order in which expressions are evaluated. This, in some cases, can determine the overall value of the expression. For example, take the following expression:
 Y  =  6  + 4/2

Depending on whether the 6+4 expression or the 4/2 expression is evaluated first, the value of y can end up being 5 or 8. Operator precedence determines the order in which expression are evaluated, so you can predict the outcome of an expression. In general, increment and decrement expression are evaluated before arithmetic expression; arithmetic expression are evaluated before comparisons, and comparisons are evaluated before logical expression. Assignment expression are evaluated are evaluated last.

Operator Precedence and Associativity to Evaluate Expression: JAVA


Above Table shows the specific precedence of the various operators in Java. Operators further up in the table are evaluated first; operator on the same line have the same precedence and are evaluated left to right based on how they appear in the expression itself. For example, given that same expression
Y = 6 + 4/2

You now known, according to this table, that division is evaluated before addition, so the value of y will be 8.

You always can change the order in which expressions are evaluated by using parentheses around the expressions you want to evaluate first. You can nest parentheses to make sure that expressions evaluate in the order you want them to (the innermost parenthetical expressions is evaluated first.

Consider the following expression:
y = (6 + 4)/2

This results in a value of5, because the 6+4 expression is evaluated first, and then the result of that expression (10) is divided by 2.

Parentheses also can be useful in cases where the precedence of an expressions isn’t immediately clear. In other words, they can make your code easier to read. Adding parentheses doesn’t hurt, so if they help you figure out how expressions are evaluated, go ahead and use them.

Operator Associativity

There is a linked term – Operator Associativity. Associativity rules determine the grouping of operands and operators in an expression with more than one operator of the same precedence. When the operations in an expression all have the same precedence rating, the associativity rules determine the order of the operators.

For most operators, the evaluation is done left to right, e.g.
X  = a + b – c

Here, addition and subtraction have the same precedence rating and so a and b are added and then from this sum c is subtracted. Again, parentheses can be used to overrule the default associativity, e. g.
X = a + (b-c);

However, the assignment and unary operators, are associated right to left, e.g.,
X += y -= -4; equivalent to X  += (y  -= (-(4) ) );

Assignment and Remaining operators 

Other Remaining Operators used in JAVA Programming

All other remaining operators except assignment operators are listed in this article. Like instance of, shift operators, bitwise and many more described with example in the article.

The following table lists the other operators that the Java programming language supports.

Remaining operators used in java

In the following lines, we are discussing some of these operators. Discussion of all these operators may be large task here.

Conditional operator ?:

Java offers a shortcut conditional operator (?:) that store a value depending upon a condition. This operator is ternary operator i.e., it requires three operands. The general form of conditional operator ?: is as follows:
expressiona1 ? expression2 : expression3

If expression1 evaluates to true i.e., 1, then the value of the whole expression is the value of expression2, otherwise, the value of whole expression is the value of expression3. For instance
result = marks >= 50  ?  ‘P’ : ‘F’ ;

The identifier result will have value ‘P’ if the test expression marks >= 50 evaluates to true otherwise result eill have value ‘F’. Following are some more examples of conditional operator ? :

6 > 4 ? 9 : 7 evaluates to 9 because test expression 6 > 4 is true.
4 == 9 ? 10 : 25 evaluates to 25 because test expression 4 == 9 is false.

The conditional operator might be fascinating you but certainly one tip regarding ? :, we would like all of you to keep in mind and which is being told in form of following tip.
Beware that the conditional operator has a low precedence.The conditional operator has a lower precedence than most other operators that may produce unexpected results sometimes. Consider the following code:
n = 500;
bonus = n + sales > 15000 ? 250 : 50 ;

The above code is trying to add n and the value 250 or 50 depending upon whether sales > 15000 is true or false. But this code will not work in the desired manner. The above code will be interpreted as follows:
bonus = (n + sales) > 15000 ? 250 : 50;

Because operator ‘+’ has higher precedence over > and ?:
Therefore, for the desired behaviour the conditional expression should be enclosed in parentheses as shown below:
bonus = n + (sales > 15000 ? 250 : 50) ;

The [ ] Operator

The square brackets are used to declare arrays, to create arrays, and to access a particular element in an array. Similar data items, such as marks of 20 student or sales of 30 salesmen etc., are combined together in the form of arrays. Here’s an example of an array declaration
Float [ ] arrayofFloats = new float[10] ;

The previous code declares an array that can hold ten floating point numbers. Here’s how you would access the 7th item in that array :
arrayOfFlooats[6];

Please note that first element of array is referred to as array-named[0] i.e., to refer to first item of array namely arrayOfFloats, we shall write arrayOfFloats[0]. We are not going into further details of arrays right now.

The . Operator

The dot (.) operator accesses instance members of an object or class members of a class.

The ( ) Operator

When declaring or calling a method, the method’s arguments are listed between parenthesis ( and ). You can specify an empty argument list by using ( ) with nothing between them.

The ( type ) Operator

This operator casts ( or “ convent “ ) a value to the specified type. You’ll see the usage of this operator a title later in this chapter, under the topic Type Conversion.

The new Operator

You can use the new operator to create a new object or a new array. You’ll find examples highlighting the usage of new operator in a later section – Objects as instances of class – in this chapter.

The instance of Operator

The instanceof operator tests whether its first operand is an instance of second.
Op1  instanceof   op2

Op1 must be the name-of-an-object and op2 must be the name -of -a –class. An object is considered to be an instance of a class if that object directly or indirectly descends from that class.

Assignment and Shorthand Assignment Operators used in JAVA with Example

Java provides some assignment and shorthand operators listed in the article with example of each. The article also explains a table with all these assignment operators provided by JAVA Programming.

Like other programming languages, Java offers an assignment operator =, to assign one value to another e.g.
int x, y, z;
x = 9;
y = 7;
z = x + y;
z = z * 2;

Java shorthand Operators

Java offers special shorthand operators that simplify the coding of a certain type of assignment statement. For example,
a = a + 10; may be written as a += 10;

The operator pair += tells the compiler to assign to a value of a + 10. This shorthand works for all the binary operators in Java (those that require two operands). The general form of Java shorthand is
var = var operator expression same as var operator = expression

Following are some examples of Java shorthands:
X   -= 10; equivalent to x = x-10;
X*=3; equivalent to x=x*3;
X /=2; equivalent to x=x/2;
X%=z; equivalent to x=x%z;

Thus, we can say (=,*=, /=, %=, -=) are assignment operators in Java. The operators (*=, /=, %=, += and -=) are called arithmetic assignment operators. One important and useful thing about such arithmetic assignment operators of Java is that they combine an arithmetic operator and an assignment operator, and eliminate the repeated operand thereby facilitate a condensed approach.

The following table lists some shortcut assignment operators and their lengthy equivalents:

Shorthand assignment operators in java


Sunday, April 27, 2014

Solve Decision-Making Expression using Logical Operators in JAVA

Relational operators often are used with logical operators (also known as conditional operators sometimes) to construct more complex decision-making expression. The Java programming language supports six conditional operators-five binary and one unary-as shown in the following image.


The logical OR operator (||)

The logical OR operator (||) combines two expressions which make its operands. The logical OR (||) operator evaluates to Boolean true if either of its operands evaluate to true.

This principle is used while testing evaluating expressions. Following are some examples of logical OR operation:

  • (4= =4) || (5 = =8)    results into true because first expression is true.
  • 1 = = 0 || 0 > 1         results into false because neither expression is true (both are false).
  • 5 > 8 || 5 < 2            results into false because both expression are false.
  • 1 < 0 || 8 > 0            results into true because second expression is true.

The operator || (logical OR) has lower precedence than the relational operators, thus, we don’t need to use parenthesis in these expressions.

The logical AND operator (&&)

The logical AND operator, written as &&, also combines two expressions into one. The resulting expression has the value true only if both of the original expression (its operands) are true. Following are some examples of AND operator (&&).

  • (6 == 3) && (4 == 4)           results into false because first expression is false.
  • (4 == 4) && (8 == 8)           results into true because both expressions are true.
  • 6 < 9 && 4 > 2                     results into true because both expressions are true.
  • 6 > 9 && 5 < 2                     results into true because both expressions are false.

Because logical AND operator (&&) has lower precedence than the relational operators, we don’t need to use parentheses in these expressions.

The logical NOT operator (!)

The logical NOT operator, written as "!", works on single expression or operand i.e. it is a unary operator. The logical NOT operator (!) negates or reverses the truth value of the expression following it i.e. if the expression is true, then expression is false, and vice versa.

Following are some examples of logical NOT operation:

  • ! (5 ! = 0) results into false because 5 is non zero (i.e., true)
  • ! (5 >2) results into false because the expression 5>2 is true.
  • !(5>9)  results into true because the expression 5>9 is false.

The logical negation operator "!" has a higher precedence then any of the relational or arithmetic operators. Therefore, to negate an expression, you should enclose the expression in parentheses:

!( x > 5 ) will reverse the result of the expression x > 5
    Whereas! x > 5 is equivalent to ( ! x ) > 5

i.e., it will first reverse the truth value of x and then test whether the reverse of x’s truth value is greater than 5 or not.

Relational Operators in JAVA

Compare Values using Relational Operators in JAVA

In the term relational operator, relational refers to the relationships that values (or operands) can have with one another. Thus, the relational operators determine the relation among different operands.

Java provides six relational operator for comparing numbers and characters. But they don’t work with strings. If the comparison is true, the relational expression results into the Boolean value true and to Boolean value false, if the comparison is false. The six relational operators are:

  • < (less than)
  • <= (less than or equal to)
  • == (equal to)
  • > (greater than)
  • >= (greater than or equal to) and
  • != (not equal to)

Summarizes the action of these relational operators.

Compare Values using Relational Operators in JAVA

t represents true and f represents false.
The relational operators have a lower precedence than the arithmetic operators. That means the expression
a + 5 > c – 2  ...expression 1
Corresponds to
( a + 5 ) > ( c – 2 ) ...expression 2
And not the following
a + ( 5 > c ) -2  …expression 3

Though relational operators are easy to work with, yet while working with them, sometimes you get unexpected results and behavior from your program. To avoid so, we would like you to know certain tips regarding relational operators.
Do not confuse the = and the = = operators.
A very common mistake is to use the assignment operators (=) in place of the relational operator (==). Do not confuse the testing the operator (==) with the assignment operator (=). For instance, the expression
Value = 3
Tests whether value is equal to 3? The expression has the Boolean value true if the comparison is true and Boolean false if it is false.

But the expression
Value = 3
Assigns 3 to value. The whole expression, in the case, has the value 3 because that’s the value of the left-hand side.
Avoid equality comparisons on floating-point numbers.
Floating-point arithmetic is not as exact and accurate as the integer arithmetic is. For instance, 3 X 5 is exactly 15, but 3.25 X 5.25 is nearly equal to 17.06 (if we are working with number with 2 decimal places). The exact number resulting from 3.25 X 5.25 is 17.0625.

Therefore, after any calculation involving floating-point numbers, there may be a small residue error. Because of this error, you should avoid the equality and inequality comparisons on floating-point number.
The relational operators group Left-to-right i. e., a <b<c means (a <b) < c and not a < ( b < c ).

Postfix version of operators 

Monday, March 3, 2014

Increment and Decrement Operators in Java Programming

Earlier article was about the operators in java with some of the binary operators, example of each. This article is about plus (+) operator and increment/decrement operator in brief.

Operator + with strings

Programmer have used the operator ‘+’ with numbers. When you use + with numbers, the result is also a number. However, if you use operator + with strings, it concatenates them for example:

(5 + 6) results in to 11.
(“5” + “6”) results in to “56”.
(“17” + “A, V. Vihar”) result in to “17 A, V. Vihar”
(“abc” + “123”) results in to “abc 123”
(“” + 5 + “xyz”) results in to “5xyz”
(“” + 5) results in to “5”

(In above two expressions Java would internally convert 5 in to “5” first and then concatenate with “xyz” and “” respectively.)

Increment/Decrement Operators (++, --)

Java includes two useful operators not generally found in other computer languages (expect C and C++). These are the increment and decrement operators, ++ and --. The operators ++ adds 1 to its operand, and – subtracts one.

In other words,
a = a + 1;        same as   ++a ; or a++;
And
a = a – 1          same as --a ; or a --;

However, both the increment and decrement comes into two varieties: they may either precede of=r follow the operand. The prefix version comes before the operand (as in ++a or --a) and the postfix version comes after the operand (as in a++ or a--). The two version have the same effect upon the operand, but they differ when they take place in an expression, that would be discussed in later articles.
© Copyright 2013 Computer Programming | All Right Reserved