Deep understanding of the differences between i++ and ++i in Java _java

Source: Internet
Author: User

Today, a simple talk about Java, I believe that a lot of friends just started learning Java will encounter this problem, although the problem is very simple, but often easy to confuse, say Java i++ and ++i difference.

First look at the code:

<span style= "FONT-SIZE:18PX;" >public class Test {public
	static void Main (string[] args) {
		int i = 0;
		for (int j = 0; J < J + +) {
			i=i++;
		}
		SYSTEM.OUT.PRINTLN (final result of "I" +i);
	}
</span>

We can see the result at a glance, how much is the result? Is it 10?

Believe that there are many friends at first glance, think the answer is 10, the correct answer is: 0;

Just beginning to learn the C,java, the teacher has spoken of the form of self: namely: i++ and ++i;

In fact, the difference is that i=i++ is the first assignment in the self increase, so no matter how many times, the left of I is always 0, the final result is 0. To I=++i, can achieve the effect, ++i is the first increment in the assignment.

You can understand this by looking at the code:

<span style= "FONT-SIZE:18PX;" >public class Test {public
	static void Main (string[] args) {
		int i = 0;
		for (int j = 0; J < J + +) {
			i=i++;
		}
		SYSTEM.OUT.PRINTLN (final result of "I" +i);
	}
	
	
	The public static int count (int i) {
		//TODO auto-generated Method Stub//
		is selected to save the initial value, JVA open the temporary variable area
		int temp=i;
		Do self increase
		i = i++;
		Returns the original value return
		temp
		

	;
}
</span>

So to achieve the increase can be used i=++i, but generally direct use of i++, so better; This is also a Java's self-increasing trap.

The above in-depth understanding of the Java i++ and ++i is the difference between the small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.