Why use int over double?

i am using the book beginning java 2. and there is a example showing how the math class works
the program calculates the radius of a circle in feet and inches given that the area is 100 square feet:
public class MathCalc
public static void main(String[]args)
double radius = 0.0;
double circlearea= 0.0;
int feet = 0;
int inches = 0;
radius = Math.sqrt(circleArea/Math.PI);
feet = (int)Math.floor(radius);
inches = (int)Math.round (12.0 * (radius-feet));
System.out.println( Feet + "feet" + inches + "inches");
the output will be 5 feet 8 inches.
my question is why bother with using 'int', why not simply use 'double' for all your variables?
in feet and inches 'int' has been used as the result would have been a floating value. so casting as been used. But doesnt that complicate things?cant one just use long for all variables and forgot about worrying whether the value will fit or not.
thanks
Ali

i am using the book beginning java 2. and there is a
example showing how the math class works
the program calculates the radius of a circle in feet
and inches given that the area is 100 square feet:
public class MathCalc
public static void main(String[]args)
double radius = 0.0;
double circlearea= 0.0;
int feet = 0;
int inches = 0;
radius = Math.sqrt(circleArea/Math.PI);
feet = (int)Math.floor(radius);
inches = (int)Math.round (12.0 *
d (12.0 * (radius-feet));
System.out.println( Feet + "feet" + inches +
"inches");
the output will be 5 feet 8 inches.
my question is why bother with using 'int', why not
simply use 'double' for all your variables?There are several reasons to use int (when appropriate) rather than double. More generally, there are several reasons to use integer arithmetic instead of floating point.
First, integer arithmetic is precise whereas floating point arithmetic is always subject to imprecision. E.g. 6 / 2 always equals 3, 6.0 / 2.0 may equal something like 3.000000000000001.
Second, (related to the above) the results of integer arithmetic operations will not vary from one machine to the next. The results of the same floating point operation may vary from one machine to the next.
Third, integer arithmetic is always faster than floating point.
>
in feet and inches 'int' has been used as the result
would have been a floating value. so casting as been
used. But doesnt that complicate things?The results are cast back to an int because it would look silly and meaningless to print a result of, for instance, 5.00000001 feet, 8.00045 inches.
cant one just
use long for all variables and forgot about worrying
whether the value will fit or not. No. You should never disregard whether the results of arithmetic operations will overflow the size of the word you are using. Even though a long type can contain a pretty huge number, you can still easily overflow it and get nonsensical results.
Also, a 32 bit word is the native size for most of the machines most of us use. This means that arithmetic operations are fastest on int types (for most of us). This shouldn't be a primary design consideration but it should be taken into account.

Similar Messages

  • Curious to Know why use iCal over PalmDesktop

    Hello all,
    Please feel free to provide experiences and thoughts on the benefits of using iCal vs. PalmDesktop.
    I have recently made the switch from PC - and am still in the new play phase with all of the programs avail. to Mac users. I am sure there are reasons both good and bad for using certain programs, just figured the crew here on the Apple forums would be great place to start.
    Thanx,
    -Al-
    iBook & MBP

    I needed a scheduler app a few months after iCal came out. It didn't do all the scheduler tasks I needed it to do that you can find in all the other apps but it looked like a great program, even though it was very rough around the edges. I decided to go with iCal over palm because I thought the palm app, though very advanced and did everything I needed it to do, would be discontinued soon and wouldn't be guaranteed to work in future Mac OS updates and because I thought even though iCal still needed a lot of work, it was just released so surely it would get much better soon. I made the wrong choice. Not only does palm do everything, it also still works and probably will continue to work for another decade. iCal on the other hand has not seen a significant update in a couple of years and is still almost as incomplete and rough around the edges as it ever was. Don't make my mistake man, now my workflow and event history is locked into iCal and it's too late to change. Palm is uglier but it does the job much better.
    I come to this forum every few months to see if there's been any movement in iCal that I don't know about, but there never is. I've sent Apple a zillion messages and feedbacks telling them to give iCal a significant update already, but they seem to have all but abandoned this app. When I read about projects that are planned for newer versions of the Mac OS I never see any sign that they are doing any work on this app at all. If anybody has information to the contrary I'd love to hear it, but for now I'd have to advise you to not hitch your wagon to this program that Apple treats like a redheaded step child.

  • Why use Flex over Flash 8

    I would like to know what makes Flex more useful than Flash
    8? Is Flex basically replacing the Flash SDK? I looked into Flex a
    little bit and it looks like it has an awesome integration of Flash
    and XML. I was also wondering if Flex integrates other development
    technologies with Flash, such as PHP.
    Currently I am working for a gaming company and would like to
    get Flex pretty soon.
    -Thanks in Advance :)
    Flash Development at
    Vectorflash.net

    i think it is not "more useful" but both got different
    strength.
    flash is for animation, presentation, interactive website
    & etc but flex is more to web application.

  • Why use XE?

    Why use XE over the other versions of 10g?

    i would suggest XE isnt that good for most development work as it doesnt incoude a lot of the features a lot of "enterprise people" needs.
    Yuo should always develop and always test on the versions that you are going to deploy with.
    Dont forget you can use Oracle for free gernally in development at no cost

  • Why use mail client over web site mail inteface?

    Hello.
    I had question to all emial client user's:
    Why use mail client over web site mail inteface?
    And I have one more question.
    Is there any option to backup/compress your mail in mutt or thunderbird?

    brisbin33 wrote:
    briest wrote:
    brisbin33 wrote:Also, imap in mutt for me is sooooo slow (proportional to the size of the mailbox of course)
    Do you use header caching? It can accelerate remote imap access, but is disabled by default. Also playing with imap_idle (yes, if server supports), imap_keepalive (low) and timeout (high) may produce nice results.
    i've tried everything (always caching, and setting various imap_* options).  trust me.  it's funny, it wasn't bad at first, then one day i'd hit j/k and 3 seconds later the indicator would move... that's when i set up offlineimap.
    I'm very happy with this maildir setup now .  thanks anyway tho.
    OMG, mutt is flying right now! Even with header and message cache is mutt + imap not the fastest. I reccomend offlineimap for everyone.

  • Why does the Java API use int instead of short or byte?

    Why does the Java API use int if short or even byte would be sufficient?
    Example: The DAY_OF_WEEK field in Calendar uses int.

    One of the point is, on the benchmark tests on Java performance, int does far better than short and byte data types.
    Please follow the below blog talks about the same.
    Java Primative Speed
    -K

  • Why was there over ten thousand file in my "All My Files" on my new MBP. I'm very new at using ICloud. I don't understand syncing vs time vs time vs syncing! I simply have not idea how to manage my file now.

    Why is there over ten thousand file in my "All My Files" on my new MBP. I'm very new at using ICloud. I don't understand syncing vs time vs time vs syncing! I simply have not idea how to manage my files now. I read short comments & how to's in the support sections, but nothing I've read so far explains"best practices" or turning iCloud off to get a grip on managing files. I have 250gb fast storage on the MBP itself, and 200gb in the ICloud, one would thing that's enough. The files seem too be multiplying like rabbits. IPhoto's Faces has created hundereds of "somethings" not sure what. I am sure I am very frustrated! Please comment with kindness.

    gf raines wrote:
    Yes,I am confused. To say its just another drive is a "buzz statement".
    OK, for example. If I download a document, song, or photo from ICloud, as I understand, it goes to Download in Finder. If I want to move it to a local folder of my choice on the solid state drive in my new MBP, does a copy always stay in ICloud? How do you housekeep? I have always  used to a physical drive. What is different about the mind set.  I used ICloud to store the contents of my old MBP. Once I download all the files I need, should I turn off ICloud and manage the file locally? I don't like the automatic movement of files when I don't understand the locations.
    Nope, you don't understand it.
    If you download a song from the iTunes cloud storage (which is not iCloud) it goes into the iTunes music folder (generally to a subfolder therein)
    If you download a document from the iCloud drive it will go wherever you chose to put it.
    If you download a photo from the iCloud Photo library it will also go wherever you choose to put it.*
    If you move something you have not copied it, if you want to keep a copy on the iCloud drive and in a local folder, you would copy, not move it.
    There is no 'automatic' movement, you decide what to store on the iCloud drive (exactly like any other drive) and what to remove.
    The iCloud drive appears as a folder in Finder, you use it just like any other, copy/paste, save, delete etc.
    You can turn the iCloud drive off whenever you like, download the content to a local drive first.
    * Because the iCloud drive appears as a folder in Finder there is in fact no need to ever download anything to your Mac, everything on the drive is already on your Mac.

  • Why would you use JavaFX over JavaEE or JavaSE?

    Just curious why you would use FX over the others? Is it because of the GUI, and some added features, or what makes FX better?
    Also what exactly is the differences between the 3? It seems like SE is the basic, then EE is used for client-server and maybe security and such? FX seems to just have advanced GUI and stuff like that? Does anyone have a link or a list of what features are different and such?
    Thanks a lot!!!
    ~KZ
    Edited by: KonradZuse on Jul 6, 2012 8:41 AM

    KonradZuse wrote:
    I usually use swing, but I am starting a new business application for real world use, so I want it to be the best it can be. FX's Gui is great, but is it worth it to start using that right away? I also want to be able to use 3D, and as someone said you can do 2D in a 3D space, so that is basically what I need for now, but I would like to be able to do full 3D.JFX isn't exactly built to do 3D stuff right now. But neither is Java2D (the base for AWT and Swing), so nothing is different really.
    So what I really want to know is what is the differences between SE and EE?One is "Java", the other is a specification. For more information I refer to Google.

  • I am getting the error message "could not copy to requested location" to a drive i have been using for over a year... when I do the same thing to another drive - it works just fine. why?

    i am getting the error message "could not copy to requested location" to a drive i have been using for over a year... when I do the same thing to another drive - it works just fine. why?

    Possibly the drive is full
    Possibly the permissions are not set to WRITE permission
    Possibly there has been a "user mistake" and you think you are copying to a drive you have been using for over a year but something has accidentally changed and you're copying to a different location

  • Why use Non-Interactive Adobe forms over Smart-Forms

    Hi,
       Is there any advantage of using Adobe over Smart-forms. We do not need Interactive forms. I know this is a new approach which SAP is using, but other than that is there any good reason?

    better look and fill..
    better scope of development.
    reusable interfaces
    digital signatures.
    use of scripting languages.

  • Why would you use Java over C/C++

    This thread :
    http://forum.java.sun.com/thread.jspa?threadID=689490
    Brought back to mind a problem I had in the first C program I worked on -
    I'd declared an array and a file pointer on the stack in a function, overwrote the end of the array by mistake, and trashed the file pointer. The file pointer was used a while after the array was overwritten - took me 2 days to work out what was happening. Array overwrites like this are just not possible in Java - that's a reason to use Java over C or C++.
    Anyone else got their own scare stories like this ? Maybe someone's got a Java scare story that would make you use C ?

    A C++ based bond trading system had the description database varchar field width of 60 characters. The GUI software to display this had buffers 60 characters wide. New bonds came along with widths of over 60 characters so the database field width was changed to 80 characters but nobody told us (the GUI maintenance team) about the change.
    There was no real problem for about 4 days after the first long named bond was inserted. Then, at random times, the GUI application would crash. It took many many days to find the source of the problem and to fix it. The blame was laid at the door of the GUI maintenance team even though we had not written the code and we had logged the potential problem in the bug database months before but management decided that it was not a problem so should not be 'fixed'.
    This literally cost millions because the traders could not be sure of their positions.
    I left as soon as my contract ran out.

  • Dimensions - int and double mixed?

    Dimension x = new Dimension(int_1, int_2);
    int height = x.height;
    int width  = x.width;
    double height_d = x.getHeight();
    double width_d = x.getWidth();When you create a dimension you give it to integers as the width and height. However, if you call getHeight() or getWidth() it returns double-precision values. What's the point? Why does it use int/doubles?
    Thanks

    The methods getWidth/getHeight are inherited from RectangularShape.
    We have:
    Rectangle2D extends RectangularShape
    Rectagle extends Rectangle2D //implemeted with ints
    Rectangle2D .Float extends Rectangle2D //implemeted with floats
    Rectangle2D .Double extends Rectangle2D //implemeted with double
    So the implementations are providing the precision. Since the getWidth/getHeight methods are common
    to the hierarchy they return doubles to avoid loss of precision in the Rectangle2D .Double case.
    On the other hand, if I'm working with a java.awt.Rectangle I just access the public width and height fields
    directly.

  • Int and Double help

    I have a new lab and have most everything down right except that I am trying to create an int array that has double methods within it here is what I have so far:
           public static void main(String[] args) {
                   Scanner in = new Scanner(System.in);
                   System.out.print("How many numbers? ");
                   int numNum = in.nextInt();
                   System.out.print("How many intervals? ");
                   int intervals = in.nextInt();
                   System.out.print("\nHistogram");
                   System.out.print("\n--------------------------------------------------------");
                   double[] n = Generator.getData(numNum);
                   double min = getMin(n);
                   double max = getMax(n);
                   double range = max-min;
                   double width = (range/intervals);
                   int[] histogram = new int [intervals];
                   for(int index = 1; index <= intervals; index++){
                           if(index <= intervals){
                                   histogram[index] = ();
                   for     (int i = 1; i <= intervals; i++){
                           System.out.print("\n   " + i);
                           System.out.print(" " + range);
                   System.out.print("\n--------------------------------------------------------");
           private static double getMin(double[]n){
                   double lowest = n[0];
                   for (int index =1; index < n.length; index++){
                           if (n[index] < lowest){
                                   lowest = n[index];
                   return lowest;
           private static double getMax(double[]n){
                   double highest = n[0];
                   for (int index =1; index < n.length; index++){
                           if (n[index] > highest){
                                   highest = n[index];
                   return highest;
           private static int getArray(double[]n,double intervals, double width){
                   int[] array = new int [intervals];
                   for(int index=0; index <= intervals; index++ ){
                           if(index <= intervals){
                                   array[index] = (n[index]/width);
                   return array;
           }I am stuck of the getArray class. Any help is greatly appreciated.

    haphilli wrote:
    I appreciate the help I am still just not getting it it is supposed to return this:
    How many numbers? 100
    How many intervals? 10
    Histogram
    1 ****(4)
    2 ******(6)
    3 ***********(11)
    4 *****************(17)
    5 **************************(26)
    6 *************************(25)
    7 *******(7)
    8 ***(3)
    9 (0)
    10 *(1)
    The program performs the following actions:
    1. Ask the user to enter the number of numbers that will be generated and the number of intervals that will be used in the histogram, and input the two values;
    2. Generate the required number of pseudo-random numbers by using the double[] Generator.getData(int n), which, given the number of numbers to generate, n, returns an array of double of size n containing the generated numbers;
    3. Compute the range of data values (by finding the maximum and the minimum and taking their difference); then compute the width of each equally-sized interval (by dividing the whole range by the number of intervals specified by the user); finally, compute the number of data numbers falling in each interval and store these frequencies in an array of integers;
    4. Output the histogram of the data as displayed in the sample run above: each bar starts with an index (1 through the number of intervals), followed by a number of '*' equal to the number of numbers in that range, followed by the number of '*' in parentheses.
    Note: Pay attention to detail. Make your output look like the output in the sample run. However, note that your program must be able to produce the correct histogram for arbitrary data, not just for the specific data generated by Generator.getData().Yes, but we're thus far not addressing the proper operation of your code - we're still in the debugging phase.
    After the code compiles cleanly, and you get all the obvious "mechanical" things fixed, then we can start addressing the design.
    Why do I say that? Ordinarily the design comes first. But there are some syntax issues that really need to be addressed before you can appreciate what is wrong with the logic flow. You can work out the design in your head, but let's fix syntax errors before we code it up, so that we all have a good understanding of the the mechanicals.

  • Why Using Top Link is best in DB Adapter?

    Hi All,
    Can any one suggest , Why Using Top Link (Build-in Insert, Select etc. operation) is best in DB Adapter over using custom query?
    Thanks

    Hi Vikky,
    for insert/select it depends on what kind of user you are. TopLink lets you browse and click on a tables and have everything generated for you. If you are more a DBA or show me the SQL type then you can just type SQL directly.
    Some advantages of TopLink would be:
    -The range of SQL generated by TopLink is limited, but if you hard code complex SQL into your service you need to maintain it.
    -TopLink can generate at runtime the correct SQL for a given database, making switching from say DB2 to Oracle easy.
    -The merge operation will compare the input XML to the columns on the database and update only what has changed. It can also do a sparse merge. If only 4 columns in the XML were set, only those 4 columns in the database will be updated.
    -For inbound polling the strategy used (LogicalDelete, Sequencing Table, etc) is a configuration property and then at runtime multiple SQL statements are generated. The SQL also takes advantage of advanced syntax like the Oracle-only FOR UPDATE SKIP LOCKED, writing it all yourself may be tedious and error prone.
    -The main benefit of TopLink is when you go beyond thinking about a single table. If you import multiple related tables at once, TopLink will generate the SQL to select from and maintain multiple tables, establish a commit order, and generate a hierarchical XSD. With custom SQL the matching XSD is always flat. I.e. if you just need to insert an emp you could get away with custom SQL. If you need to insert a dept and emps, I would use TopLink.
    -This is also when the intermediary abstraction of an object/table makes more sense, as you only need to import a complex relational schema once, then generate inserts, selects, etc.
    So I hope that helps. They are each equally viable and can do something that the other can't. Where you see an overlap I would go with personal preference.
    Thanks
    Steve

  • Why use interlaced ?

    We shoot with DVCpro50 at 24p.
    A few questions.
    1. Is there anytime that there is an advantage, or a time when you have to use field dominance ?
    Interlaced footage looks like crap. Stills look horrible in an interlaced timeline - why ever use it ?
    It seems I can just switch the field dominance from "lower/even" to "none" and everything looks 10 times better on computer and NTSC monitor.
    2. Is there anytime that there is a disadvantage to removing the pulldown and editing in 24fps. It looks 10 times better without the screwd up "B/C & C/D" frames if you leave it in and edit at 29.97fps.
    3. is there any advantage or quality enhancement by removing the pulldown in "Shake" rather than letting FCP do it while capturing. And after removing, should your sequence timeline be set to 24fps or 23.98fps and why ?
    4. Have G5, OSX 10.4.8, AJA IO hooked up to NTSC monitor, and can't view 24fps timeline on external NTSC monitor - only frames when parked - is that because these monitors will only accept 29.97 field dominated footage ?

    Fist off - thanks for the help on part 4.
    I know how TV works and why NTSC was invented over a half century ago.
    Now that I can monitor on the external I will always edit in 24. I'm only the editor - they shoot with a SPX900 in 24p - if you don't remove the pulldown, frames 3 & 4 out of the 5 frame cycle combined with the interlacing gives really bad results. So out of curiosity I switched the sequence dominance setting from "lower/even" to "none" - at this point is ii still treated as interlaced or if it is set to "none" is it now progressive, like when you are editing in 24 and the field dominance window is greyed out. I would think that this would look jittery on a TV because the field order isn't right - but it doesn't - I can make DVD, VHS(not sure why), and monitor and the only difference is that the stills look incredibly better - there's no banding and stair stepping on the shoulders- on either the computer monitor or the NTSC monitor. And with it set to "lower/even" the bigger the computer or TV screen the worse it looks - but with it set to "none" the stills just get softer as you view them on bigger screens as if the right amount of gaussian blur was being added automatically - Isn't that wht you want ?
    So that was why I ask "why use interlace" if you have a choice?
    I'm not trying to be cool - these are ligitimate questions. I consider this doing my homework - isn't that what forums are for - I help people with answers all of the time.
    As for part 3 - Does "standard pulldown" refer to going back & forth between 24fps (film) and 29.97 (video) and "advanced pulldown" from 23.98 to 29.97 ?
    Are all of these modern video cameras actually shooting at 23.98 ?
    2 G5s 1.8Ghz single & 2.7Ghz Dual (PPC)   Mac OS X (10.4.8)   FCP Studio 5.0.4, Shake 4.1, AJA IO, 1.5G RAM & 3G RAM
    2 G5s 1.8Ghz single & 2.7Ghz Dual (PPC)   Mac OS X (10.4.8)   FCP Studio 5.0.4, Shake 4.1, AJA IO, 1.5G RAM & 3G RAM

Maybe you are looking for