2 Replies - 107 Views - Last Post: 02 July 2012 - 07:55 AM Rate Topic: -----

#1 unleashed-my-freedom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 13-January 10

Is it the same?

Posted 02 July 2012 - 07:44 AM

I had tried this coding myself but I had a different answer from the solution given. May I know if it is the same?

//calculate the mass
long massOfTheBlock = length * width * height * density

System.out.println("Length of the block, in cm is " + length);
System.out.println("Width of the block, in cm is " + width);
System.out.println("Height of the block, in cm is " + height);
System.out.println("The mass of the block is" + massOfTheBlock "grams")


AND


System.out.println("Height of the block, in cm is " + height);
System.out.println("");
// Calculate and print the block's mass.
System.out.println("The mass of the block is "
+ (length * width * height * AL_DENSITY) + " grams");


Is This A Good Question/Topic? 0
  • +

Replies To: Is it the same?

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 9042
  • View blog
  • Posts: 33,544
  • Joined: 27-December 08

Re: Is it the same?

Posted 02 July 2012 - 07:47 AM

Your first snippet won't compile as you are missing a semi-colon at line one. Second, if the variables don't hold the same values in both snippets, you won't get the same answer.
Was This Post Helpful? 0
  • +
  • -

#3 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon

Reputation: 5437
  • View blog
  • Posts: 8,755
  • Joined: 19-March 11

Re: Is it the same?

Posted 02 July 2012 - 07:55 AM

Also, after the first block runs, you have the variable massOfTheBlock containing a value, whereas in the second you only calculate it and display it.

Depending on the situation, either of these can be correct. If you won't be referring to the value again, you shouldn't keep it, but if you need it again, it's generally more efficient to store it than to calculate it again.

In this situation, neither the space of a long nor the time to do the multiplication is going to be significant, but when the calculations and the objects get larger, this becomes a consideration.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1