Java: double to int automatic conversion

Tushar Sharma

Tushar Sharma

@tushar-sharma-1ATorv Oct 22, 2024
int i = 1;
i = i + 1.2; 

would result in compile time error. I understand that i + 1.2 would result in a float which can't be assigned to integer.

This code is error free and the result is an integer.

int i = 1;
i += 1.2; 

This automatic narrowing is mind boggling.

Edit:
Had been searching for answer the whole day and someone finally answered it.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
from: #-Link-Snipped-#

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • PraveenKumar Purushothaman

    PraveenKumar Purushothaman

    @praveenkumar-66Ze92 Mar 2, 2011

    It is possible with an increment operator but instead you can do one thing. Type casting it to UpCast or DownCast, makes the program 100% error free!
    Eg:

    int i = 1;
    i = (int)(i + 1.2);