1

If I call

methodName(5, 1/2);

and it has the signature

public static int methodName(int x, double y){
}

does the methodName receive y with a value of 0 or 0.5?

1
  • 1
    Why just don't try it? Commented Nov 11, 2013 at 16:41

5 Answers 5

3

int y = 1/2;

At this point, y is 0. If you try to cast it to a double afterwards it will be 0.0. It doesn't remember how it got its value, just what its value is.

EDIT: I think the compiler will actually replace 1/2 with 0 at compile time. Making the code literally identical to int y = 0

Sign up to request clarification or add additional context in comments.

Comments

1
int y = 1/2;

In this code, y will be 0;

If you want to get it as 0.5

Have a try with the following code:

double y = 1.0 * 1 /2; //y is 0.5

2 Comments

Why 1.0 * 1 / 2 when you can do 1.0 / 2?
This is just an example to indicate that we can not use 1/2 to get 0.5. We need to convert one of the int value into double value. 1.0/2 or 1/2.0
0

It will evaluate to 0.

There's not a whole lot you can do with the above code.

There should be no specific reason to store y as an int.

Try this instead:

double y = 1/2.0;

1 Comment

im having an exam today, just in case this situation shows up ^^
0
int y = 1/2

Since you're using 1 (int) and 2 (int) to make the division, it's an integer division, thus y = 0 (and remainder (%) is 1).

Comments

0

I think you are confused with parameters (the parenthesis). In java every method has a set of parameters (they might not hold values ex: exampleMethod()).

A parameter is a variable that is passed into the method, so when in your code you call:

methodName() initialize it with methodName(x,y);

the x and y inside the method are just pointers for the values you pass through the parameters. I would suggest that you name your variables differently to avoid this confusion. For example:

int x;
int y;
methodName(int argX, double argY)
{

}

Also to answer your question, an int cuts off its stored value at the decimal point, so 5.9 would round to 5 rather than 6, so if you needed a floating point variable for y, either declare it as a float or a double, either will work, but most methods in the java library are written to take doubles as parameters rather than floats

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.