27.04.2013 Views

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

String, text, numbers, I/O II part<br />

Check out the % (modulus) operator, it computes the remainder.<br />

public int modMethod(int div){<br />

if(div%2==0){<br />

return 1;<br />

} else{<br />

return 0;<br />

}<br />

}<br />

Q: How can I round a number to specified precision?<br />

I have a double field that I would like to round to 2 places of precision, however, it<br />

seems like the documentation on the round function only rounds to<br />

closest integers. So that I would not be able say .3658585859 = .37 as<br />

I would like.<br />

Answer: can you scale the number up and then down again when you are finished?<br />

e.g. 0.3658585859 * 100 = 36.58585859<br />

round(36.58585859) = 37<br />

37 / 100 = 0.37<br />

I understand that bitwise operations change the 0/1 bits of a number. Question is<br />

why?<br />

I suppose it's interesting that you can manipulate numbers this way, but I can't think<br />

of a practical use for doing that.<br />

Can anyone help me understand when are bitwise operations used and why you<br />

would use them?<br />

Answer: Bitwise manipulation is often used where memory consumption is critical,<br />

and a piece of information may be encoded in less that one byte, for instance. In<br />

communication software and protocols, information may be interpreted as a stream<br />

of bits where the information is encoded at the bit-level, and you use bitwise<br />

manipulation to extract the pieces of information encoded in the bytes. There are<br />

other situations where bitwise manipulation is used, as well.<br />

by Greger Ohlson<br />

Why cannot I cast from double to java.lang.Object?<br />

Q: I'm trying to build a vector, however, one of the objects that I'm passing to the<br />

vector is of type double. How do I cast the double as an object so that I may insert<br />

the value into a vector? Does this make sense? Here is the following snippet of code<br />

I was trying to use:<br />

myVector.add (1, (Object)myDouble);<br />

Of course when I try to compile I get the following message:<br />

Invalid cast from double to java.lang.Object<br />

Could someone please explain why? I realize that Object is the mother of all objects<br />

and therefore ANY reference data type "is an" Object. So therefore I shouldn't have<br />

to cast the double, right? Help, I'm a beginner!<br />

Answer: A double is not a reference type, but a primitive one. Hence, it doesn't<br />

file:///F|/350_t/350_tips/stings_text__date_numbers_io-II.htm (5 of 7) [2002-02-27 21:19:21]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!