HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Puzzles / Compound assignment operator [i += j] is not same as [i = i + j] in java

Compound assignment operator [i += j] is not same as [i = i + j] in java

We all have used syntax’s like i += j and i = i + j thousands of times in our day to day programming. In first sight, they both look similar. In fact, they will result in same output in almost all of the cases in practical cases. But, to surprise you they are not similar. In run-time, they are treated differently when i and j are of different types. Let’s look at the example below:

int i = 5;
      
double d1 = (double)i + 4.5; //necessary to satisfy compiler
i += 4.5;

System.out.println(i);
System.out.println(d1);

Output:

9
9.5

Weird. Isn’t it. Both are expected to be same as operation is same. Why they have different values? Let’s find out.

Reason

Java language specification says following:

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.

So effectively our original example code can be re-written as below:

int i = 5;
   
double d1 = (double) i + 4.5;    
i = (int)(i + 4.5); 		//Result converted to int

System.out.println(i);
System.out.println(d1);

Output:

9
9.5

So the value 9 is nothing but a result of loss of precision while converting from double to int.

Lesson Learned

Always use the compound assignment operator [i += j] very carefully. You should use only when you are dealing with similar data types. In different data types, result can be incorrect.

Happy Learning !!

References

http://stackoverflow.com/questions/8710619/java-operator
http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.26.2

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Niket kumar

    November 27, 2019

    I think the example which you have given for these concepts not match this specification. it should be something like
    int i = 5;
    double d1 = 4.5;
    i=i+d1;//this will give compile time error
    i += d1;

  2. HIMANSU NAYAK

    June 6, 2014

    Hi Lokesh,
    Haven’t seen this great catch.

    “where T is the type of E1” is the T anything to do with the Generic Type T and also please tell us if this behaviour found in all the version of Java or only on 1.5 above.

    • HIMANSU NAYAK

      June 10, 2014

      not able to find the version in spec, let me install diffrent version of java and check.

    • Lokesh Gupta

      June 10, 2014

      T has not related to generic type T. It’s a symbol to denote the type information in formula.

Comments are closed on this article!

Search Tutorials

Java Puzzles

  • Interview Puzzles List
  • Dead vs Unreachable Code
  • Palindrome Number
  • Detect infinite loop in LinkedList
  • [i += j] Vs [i = i + j]
  • HiLo Guessing Game
  • Find All Distinct Duplicate Elements
  • TreeMap Put Operation
  • String With Nth Longest Length
  • Good String Vs Bad String
  • Complete String
  • Reverse String
  • Calculate Factorial
  • FizzBuzz Solution
  • Find Missing Number From Series
  • Create Instance Without New Keyword

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)