writing console output in java - java

class HelloWorld {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
System.out.write(97);
System.out.write('\n');
System.out.write(1889);
System.out.write('\n');
}
}
output of this program is
A
a
a
How does the following line produce a as the output.
System.out.write(1889);

Because 1889 % 256 = 97. There are 256 ASCII characters, so the mod operator is used to get a valid character.

According to this answer System.out.write(int) writes the least significant byte to the output in a system-dependent way. In your case, the system decided to write it as a character.
1889 == 0000 0111 0110 0001
97 == 0000 0000 0110 0001
The right-most octet is the same for both numbers. As #Cricket mentions, this is essentially the same as taking the modulus of the number you pass in and 256.

Related

Questions about bitwise one complement operator (Java)

When I am studying bitwise one complement operator, I see some examples on the internet:
(in short)
Example 1:
int a= 15;
int b = 27;
//15 = 0000 1111
//27 = 0001 1011
The result of ~ a is -16
//-16= 0001 0000
From: https://www.youtube.com/watch?v=qfH2Fkc1ujg
If ~ is to convert 0 to 1 and 1 to 0 , why putting 0001 0000 and the result is -16?
Example 2:
Bitwise Not or Complement operator simply means the negation of each bit of the input value. It takes only one integer and it's equivalent to the ! operator.
This operator changes each binary digit of the integer, which means all 0 become 1 and all 1 become 0. The ! operator works similarly for boolean values: it reverses boolean values from true to false and vice versa.
Now let's understand with an example how to find the complement of a decimal number.
Let's do the complement of value1 = 6:
#Test
public void givenOneInteger_whenNotOperator_thenNewDecimalNumber() {
int value1 = 6;
int result = ~value1;
assertEquals(-7, result);
}
The value in binary is:
value1 = 0000 0110
By applying the complement operator, the result will be:
0000 0110 -> 1111 1001
This is the one’s complement of the decimal number 6. And since the first (leftmost) bit is 1 in binary, it means that the sign is negative for the number that is stored.
Now, since the numbers are stored as 2’s complement, first we need to find its 2’s complement and then convert the resultant binary number into a decimal number:
1111 1001 -> 0000 0110 + 1 -> 0000 0111
Finally, 0000 0111 is 7 in decimal. Since the sign bit was 1 as mentioned above, therefore the resulting answer is:
result : -7
From: https://www.baeldung.com/java-bitwise-operators#4-bitwisecomplement-
Why are the results negative?
Thanks a lot!
"Now, since the numbers are stored as 2’s complement, first we need to find its 2’s complement..." No. You're complementing too many times. You're just computing 1111 1001's value in binary, and that's -7.
In general, it is always the case that ~x == -x - 1. You can also use that to calculate the value of negative two's complement values: -x == ~x + 1, which is why you got 7: x is -7.

What does & mean as a ternary operator

I have this piece of code I'm going to translate into mips but I don't know what it means: A = B & C[0]
When I google ternary operator I can't find any mention of the &, just e1 ? e2 : e
What does it mean?
There's no ternary operator here. The expression is equivalent to A = (B & C[0]), that is A is assigned with the result of bitwise AND applied to B and C[0].
bitwise AND
Take a look at this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
And look here for an example
http://www.tutorialspoint.com/java/java_bitwise_operators_examples.htm
The & here is the binary (2 inputs) operator "bitwise and".
In this case you have:
A = B & C[0];
So A will receive the results of the bit-by-bit and-ing of B and C[0].
Lets imagine that A, B and C[0] are two 32 bit integers, that have values I randomly assigned them, and lets view this operation in binary:
B = 0000 0001 0010 0100 1000 1001 1011 1111
C[0] = 1001 1110 1101 1101 1010 1010 1010 0101
A = 0000 0000 0000 0100 1000 1000 1010 0101 (the and of the two values above)
that is, A has a 1 bit only where both B and C[0] have 1 bits.
In decimal this is 19171775 & 2665327269 = 297125.
BTW, a ternary operator has 3 inputs, most common being ?:, as in R = C ? B : A.

BigDecimal Class in Java - Reason behind Constant values

I am working out with Java Puzzlers second puzzle.
public class Change {
public static void main(String args[]) {
System.out.println(2.00 - 1.10);
}
}
You will think the answer is 0.9. But it is not. If you workout this you will get 0.8999999. The solution given is
System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.10")));
Now it will print 0.9. I understood why it prints 0.89999. But while
I am curiously debugging BigDecimal class, I found there are many constant values substituted in most of the places. I'll list all those below and interested to know the reason behind it.
BigDecimal.java line number 394,
while (len > 10 && Character.digit(c, 10) == 0) {
offset++;
c = in[offset];
len--;
}
Here Character.digit(c,10).
public static int digit(char ch, int radix) {
return digit((int)ch, radix);
}
Here 10 is passed as radix.
Q1. Why 10 is passed there.??
BigDecimal.java line number 732
int sign = ((valBits >> 63)==0 ? 1 : -1);
int exponent = (int) ((valBits >> 52) & 0x7ffL);
long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
: (valBits & ((1L<<52) - 1)) | (1L<<52));
exponent -= 1075;
Q2. If you look into the code in depth, you can understand what the valBits is, and I am unable to understand why rightshift is used some where?
Q3. Here also you can see there as many constants like 63, 52 are used. Why?
Q4. I can understand that the hexadecimal 0x7ffL used here will increase the speed of execution. Again why BitWise & operator is used there with the hexadecimal constant.
I hope my question is clear. Sincerely your patience is appreciated.
Q1: Of course, the radix is the base of the computation. You're are using a digit in base 10 ;)
Q4: 7ff in binary: 0111 1111 1111
If you read the explanation of the bit shift operators, Java "Bit Shifting" Tutorial? you will see that >> 63 discard the 63 first bits and keep the last one. The last bit is the sign bit (for signed types). If it is 1 then the integer is negative, hence the int sign there.
Also, you can refer to https://en.wikipedia.org/wiki/Floating_point for the definition of the floating point. The 52 is to distinguish between exponent and significand.
Q4: Of course, for the exponent, you don't want to use the 'sign' bit in it, since it's not a part of the exponent, hence the mask with 7ff. The Bitwise & 0x7ff just do that; it will only put a 0 on the first bit, and leave the other to the same state. (see the truth table of the 'AND' operator https://en.wikipedia.org/wiki/Truth_table)
Edit:
Q4 complementary: If the exponent is for example 12, then the first bit will be something like:
0000 0000 1100 ... (positive value) (ex: 1x10^12)
1000 0000 1100 ... (negative value) (ex: -1x10^12)
But: 1000 0000 1100 is 2060 decimal.
if you apply the 'mask':
1000 0000 1100 & 0111 1111 1111 -> 0000 0000 1100 (12 decimal)
AND
0000 0000 1100 & 0111 1111 1111 -> 0000 0000 1100 (12 decimal)
That's what the 0x7ff is for.

Anding with 0xff, clarification needed

In the following snippet consider replacing line 8 with commented equivalent
1. private static String ipToText(byte[] ip) {
2. StringBuffer result = new StringBuffer();
3.
4. for (int i = 0; i < ip.length; i++) {
5. if (i > 0)
6. result.append(".");
7.
8. result.append(ip[i]); // compare with result.append(0xff & ip[i]);
9. }
10.
11. return result.toString();
12. }
.equals() test confirms that adding 0xff does not change anything. Is there a reason for this mask to be applied?
byte in Java is a number between −128 and 127 (signed, like every integer in Java (except for char if you want to count it)). By anding with 0xff you're forcing it to be a positive int between 0 and 255.
It works because Java will perform a widening conversion to int, using sign extension, so instead of a negative byte you will have a negative int. Masking with 0xff will leave only the lower 8 bits, thus making the number positive again (and what you initially intended).
You probably didn't notice the difference because you tested with a byte[] with only values smaller than 128.
Small example:
public class A {
public static void main(String[] args) {
int[] ip = new int[] {192, 168, 101, 23};
byte[] ipb = new byte[4];
for (int i =0; i < 4; i++) {
ipb[i] = (byte)ip[i];
}
for (int i =0; i < 4; i++) {
System.out.println("Byte: " + ipb[i] + ", And: " + (0xff & ipb[i]));
}
}
}
This prints
Byte: -64, And: 192
Byte: -88, And: 168
Byte: 101, And: 101
Byte: 23, And: 23
showing the difference between what's in the byte, what went into the byte when it still was an int and what the result of the & operation is.
As you're already working with an array of bytes here, and you're doing a bitwise operation, you can ignore how Java treats all bytes as signed. After all, you're working on the bit level now, and there is no such thing as "signed" or "unsigned" values on the level of bits.
Masking an 8-bit value (a byte) with all 1's is just a waste of cycles, as nothing will ever be masked off. A bitewise AND will return a bit true if both bits being compared are true, thus if the mask contains all 1's, then you're guaranteed that all bits of the masked value will remain unchanged after the AND operation.
Consider the following examples:
Mask off the upper nibble:
0110 1010
AND 0000 1111 (0x0F)
= 0000 1010
Mask off the lower nibble:
0110 1010
AND 1111 0000 (0xF0)
= 0110 0000
Mask off... Eh, nothing:
0110 1010
AND 1111 1111 (0xFF)
= 0110 1010
Of course, if you were working with a full blown int here, you'd get the result at the others have said: You'd "force" the int to be the equivalent of an unsigned byte.
In this example, I don't see how it would make any difference. You are anding the 0xff with a byte. A byte by definition has 8 bits, and the add masks off the last 8 bits. So you're taking the last 8 of 8, that's not going to do anything.
Anding with 0xff would make sense if the thing you were anding with it was bigger than a byte, a short or an int or whatever.
This should only make a difference if there are negative bytes. & 0xff is typically used to interpret a byte as unsigned.

integer assigning in java

public class Example {
public static void main(String args[]) {
int a = 0153;
int b=a;
System.out.println(""+b);
}
}
Can someone explain why it prints 107 and not 153?
Octal of 107 is 0153
In Java you can create octal literals simply by adding a leading zero like this: int a = 0755; Be careful! It is very common to specify an octal literal
Because a number starting by 0 is considered as an octal value in Java. 0153 in octal is 107 in decimal.
You write as octal and print defaults to decimal.
Input Prints (decimal)
Decimal 153 153
^
No leading zero (digits 0-9)
Octal 0153 107
^
leading zero (digits 0-7)
Hex 0x153 339
^^
leading 0x (digits 0-F)

Categories

Resources