I was reading a book "Beginning Java 8 Fundamentals". And I saw this line:
//some code...
sum = sum + i; // Better to use sum += i
//more code...
Then here is my doubt: Is that true? Why is better to use +=
operator? I thought that +=
operator was only a more simplified expression? If I use one or other which implications there are in the code performance?
5 Best Practices When Coding in Java As a Java developer, these are some of the best practices you should try out while writing codes for your next projects: Using Naming Conventions. Ordering Class Members by Scopes. Class Members should be private.
I think, the book offers to use +=
as best practice. Indeed, there is no difference between 2 statements of sum += i
and sum = sum + i
I implement 2 classes each include one statement and watch the byte code with command javap
Here is program 1:
public class Program1 {
public static void main(String []args) {
int i = 1;
int sum = 2;
sum += i;
}
}
Here is the byte code:
public class Program1 {
public Program1();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iconst_2
3: istore_2
4: iload_1
5: iload_2
6: iadd
7: istore_1
8: return
}
Here is program 2:
public class Program2 {
public static void main(String []args) {
int i = 1;
int sum = 2;
sum = sum + i;
}
}
Here is the byte code:
public class Program2 {
public Program2();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iconst_2
3: istore_2
4: iload_1
5: iload_2
6: iadd
7: istore_1
8: return
}
As seen above, the byte codes are the same, so the statements are the same. No difference.
Edit 1: How to run javap command
javac Program1.java
javap -c Program1.class
to see the bytecode.Edit 2: The difference between operators if the variable types are different
+=
operator has an implicit cast to left operant, so if the variables differ in its types +=
operator wil automaticaly cast.
Here is the code
long i = 1;
int sum = 2;
sum += i; //means sum = (int)(i + sum)
Furthermore, sum = sum + i
do not have implicit cast, this statement will not compile.
I generaly use explicit casting, if there is need to cast. This make the code more readable and safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With