cresjoy cresjoy - 1 year ago 346
Java Question

.getWidth(), .getHeight() in Java

So I just started learning Java yesterday coming from a different language, and I am reading through my textbook and finding it to be pretty nice so far. However I did an exercise that basically required me to create a new Object use Rectangle and find the area. Below is the working code I came up with.

Now coming from other programming languages I was just toying around with this and did

int area,width,height;
and then it gave me an error saying that I had to use double in order to utilize
.getWidth();, .getHeight()
. I couldn't find anything in my book telling me why I had to make this a double and I started looking online and found this link

Now I found some documentation online where It told me to use double as well, but I'm not really sure why would I need to set these as doubles. Is it because the people who made Java, knew that precision is needed when we are working with coordinates and doing math with widths, heights and coordinates? My book says that it takes more memory to make a
variable rather than an
( I come from doing lots of javascript and PHP, so reading on what a
does was something good for me).

I.E. Why do I need to make my
variable doubles in order to use

package keepo;
import java.awt.Rectangle;
public class tuna{
public static void main(String [] args){
Rectangle rect = new Rectangle(10,20,50,40);
double area,width,height;
width = rect.getWidth();
height = rect.getHeight();
area = width * height;
System.out.println("Width is : " + width + "Height is : " + height);
System.out.println("Area is : " + area);

Answer Source

It is because this is how these methods have been defined in the java api. As you can see under the modifier and type column that the methods getWidth(), getHeight() all return value of type double.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download