Dear friends
i was playing with some conversion code yesterday when i tried to compile this:
class BytetoChar
{
public static void main(
String argv[])
{
int i=255;
byte a=(byte)i;
System.out.println(a);
char z=a;
System.out.println(z);
}
}
on compiling, i received an error which read:
BytetoChar.java:8: possible loss of precision
found : byte
required: char
char z=a;
^
1 error
A few questions:
why does it report an error when byte to char is a widening conversion ?
is it because of the signed nature of bytes and unsigned nature of chars ?
anyway, then i recomipled the code below:
class BytetoChar
{
public static void main(String argv[])
{
int i=255;
byte a=(byte)i;
System.out.println(a);
char z=(char)a;
int x=z;
System.out.println(x);
}
}
the sample output is:
-1
65535
But i was expecting an output of
-1
255
because when I convert i to a (refer above variables), the result is a narrowing conversion, hence the lower 8 bits are assigned to a, bit to bit. hence first output is ok. but next, i am widening a to z, i expect the 8 bits to assigned to the lower 8 bits of z and hence a value of 255.
Another code: (Question #34 in Brogden Exam Perp)
class ZZZ
{
XXXXX void setWidth(int n){}
}
class YYY extends ZZZ
{
YYY()
{
int a=20;
setWidth(a);
}
}
in the above code, what should be the access modifier(s) for the setWidth() method in class ZZZ (in place of XXXXX) so that YYY is allowed access to this method but other unrelated classes in other packages are not allowed to call the method.
a. private
b. protected
c. default (no modifier)
d. friend
the answer given is b and c. but I think the answer can only be b as the wording of the question clearly mentions that the method should not be accessible to UNRELATED CLASSES IN OTHER PACKAGES.
will someone explain
thanx in advance
sanjeev