Tuesday, 28 August 2007

Operations Basics

Continuing reading JLS stopped in section Operators. Hey yes these operators only. (+,-,1,%).

Reading more about Remainder Operator(%)

Can you predict the output of this program?

public class BasicOperations {

public static void main(String[] args) {

System.out.println(5%3);
System.out.println(5%(-3));
System.out.println((-5)%3);
System.out.println((-5)%(-3));

}
}


Output: Guessed 2,-2,-2,2??

Correct Output:
2
2
-2
-2

If we navigate to section "15.17.3 Remainder Operator %" in JLS it states
"
It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor. If the value of the divisor for an integer remainder operator is 0, then an ArithmeticException is thrown
"

Hence the +2 for the 2nd example operation.

Now navigating to section Additive Operators (+ and -) for Numeric Types few expection scenario's i thought to share are:

The sum of two infinities of opposite sign is NaN.

Ex:
double x=-1.0/0.0;
double y=1.0/0.0;
double z=x+y;
System.out.println(z); --> NaN

The sum of two infinities of the same sign is the infinity of that sign.

Ex:
x=1.0/0.0;
y=1.0/0.0;
z=x+y;
System.out.println(z); --> Infinity


If either operand is NaN, the result is NaN.

double k=0;
System.out.println(k+z); --> NaN


The sum of two zeros of opposite sign is positive zero.
x=0.0;
y=-0.0;
System.out.println(x+y); --> 0

The sum of two zeros of the same sign is the zero of that sign.
x=-0.0;
y=-0.0;
System.out.println(x+y); --> -0

The sum of two nonzero finite values of the same magnitude and opposite sign is positive zero.
x=-2.0;
y=2.0;
System.out.println(x+y); --> 0

Hope this helps and clears any doubts if any.

Any suggestions most welcomed.

3 comments:

Anonymous said...

Hi Prashant,
Appreciate all the knowledge you have shared. Just one question for you, i'm amazed by the number of books you read ! how do u manage to do that ?

regards,
Sapien

Anonymous said...

you are really a excellent webmaster. The web site
loading pace is incredible. It seems that you are doing any distinctive
trick. Also, The contents are masterpiece. you've performed a magnificent job on this subject!

my web page ... clear

Anonymous said...

Nice blog here! Also your site loads up very fast! What web
host are you using? Can I get your affiliate link to your
host? I wish my web site loaded up as quickly as yours lol

Here is my blog - clear