Help coderanch get a
new server
by contributing to the fundraiser

Anu Rastogi

Greenhorn
+ Follow
since Jan 08, 2007
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Anu Rastogi

Thanks Joel!!
That explanation makes a lot of sense
17 years ago
I am also in the process of preparing for JCP. So please correct me if my understanding is incorrect

A byte is represented by 8 bits of which the leftmost bit is the sign bit. This is 1 for negative numbers and 0 for positive numbers. The range for a byte is -128(1000 0000) to 127(0111 1111).

When byte a =(byte)127 is evaluated, 127 is in the range for a byte, so the output is 127.

For byte b=(byte)128, this is represented in binary as 1000 0000 which is equivalent to -128.

For byte c=(byte)255, this is represented as 1111 1111. This is a negative number. A negative of a number is found by taking 2s complement.(taking 1's complement and adding 1). So if we reverse this process on this number(subtracting 1 and taking 1s complement), we get -1.

For byte d=(byte)256, this is represented in binary as 1 0000 0000. Since this has 9 bits and a byte is represented with 8 bits, the 9th bit is discarded and we get 0 as the result.
Check out this piece of code:
public class BooleanTest1{
public static void main(String args[])
{
boolean a = false;
boolean b = false;
boolean c = false;
boolean d = (a=true) || (b=true) && (c=true);
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}

}

The result is a=true;b=false;c=false

I understand that if the first operand of || operator is evaluated to true, the second operand is not evaluated.
But the precedence of && is greater than ||. In this case, shouldn't (b=true) && (c=true) be evaluated before the operand for || is evaluated?
17 years ago