2 questions

G

gk

i have 2 questions..

Q1:Why do you create interfaces, and when MUST you use one?


Q2: can a double value be casted into byte ?how ? wont there be loss
of precison ?

double=8 bytes ? is not it ?

please respond

thanks
 
P

Paul Davis

Q1 has too many different answers to get a simple reply. Pick up a copy
of "Effective Java" and use that as your guide.

Re: Q2:
yes a double can be cast to a byte. Yes, there will absolutely be a
loss of precission. in fact, you may not even recognize your value.
double dbl = 9876.341;
byte b = (byte)dbl;
// b now equals -127

When you cast a double to a byte, the compiler will generate two
different instructions having the mnemonics d2i and i2b (double to
integer and integer to byte).
d2i basically drops any fraction and if your double is really large,
you are going to lose even more
i2b is the equivalent of copying over the last 8 bits, in other words
intVal & 0xFF

So, going double to a byte is like trying to pour eight gallons into a
one gallon bucket.
 
O

Oliver Wong

gk said:
i have 2 questions..

Q1:Why do you create interfaces, and when MUST you use one?

This one question alone is actually composed of two sub-questions. The
answer to the first sub-question is long and abstract. Read
http://java.sun.com/docs/books/tutorial/java/concepts/interface.html

For the second sub-question, it's never the case that you *MUST* use an
interface, in the Turing Complete sense; that is, for any Java program which
uses interfaces, it should always be possible to write a different program
which doesn't use interfaces, but which is indistinguishable from the first
according to the end-user.

That said, interfaces are useful in that you can implement multiple
interfaces, but only extend one class.

This next question is actually 5 questions combined together.
Q2: can a double value be casted into byte ?
Yes.

how ?

double foo = 1.0;
byte bar = (byte) foo;
wont there be loss
of precison ?

Most of the time, yes.
double=8 bytes ?

On most (all?) implementations, probably yes. However, IMHO it's better
to think of the range of values than the actual bit-width. Double ranges
between negative Double.MAX_VALUE and positive Double.MAX_VALUE.
Double.MAX_VALUE is 1.7976931348623157e+308. The actual bit-width isn't that
important. The JVM for a 128 bit processor might allocate 16 bytes for
double, for example, and just ignore the top 8 bytes.

is not it ?

That's not it. See above.

- Oliver
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top