0

I was writing a program and forgot to write Math.round() and when I was reviewing the code I saw this

int number = 1/2; 

why doesn't this raise an error of required type: int | provided:double?

Note: If this is a silly question please forgive I new to programming.

1
  • 3
    This just results in integer division. The two arguments (numbers) are treated as ints. The result will be zero as integer division truncates whatever is after the decimal point (i.e., it'll round down to the nearest integer). Commented Aug 12, 2020 at 4:43

2 Answers 2

1

its an automatic type conversion.

Here the variable 'number' stores the auto converted value to int 0.

well auto type casting doesn't always work. when you write int number = 0.5; it will give an error

but when you write int number = (int) 0.5; its called an explicit type casting and now number stores 0 value.

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

3 Comments

Actually there's no automatic type conversion in this particular example. Both operands (provided to the division operator) are plain ints, thus the operator will perform integer division.
@JanusVarmarken I am actually confused. is it casting to int or something else.
@BluNyte there is no (automatic) type conversion in your particular example since both operands provided to the division operator are treated by the compiler as ints. The division operator is defined both for ints and doubles (and the other integer and floating point types). When the division operator is supplied with two ints, it'll perform integer division (in this case on ints), and the return type of this is also an an integer (in this case an int).
1

Normally doing math operations using double will most likely be giving double on the other hand for int it will give a int.

However, if thats not the case Java will strip the number after the dot (.) and set the value to whatever is left. Example:

3/4 = 1.5 => Java => 1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.