Increment Operators

class jamesprogram {

	public static void main(String args[]){
			
		int frogs=6;
		int horses=4;
		
		++horses;
			
		System.out.println(horses);
	}
}

… gives the same output as

class jamesprogram {

	public static void main(String args[]){
			
		int frogs=6;
		int horses=4;
			
		System.out.println(++horses);
	}
}

The output we get is 5.

This is known as pre-incrementing.

class jamesprogram {

	public static void main(String args[]){
			
		int frogs=6;
		int horses=4;
			
		System.out.println(horses++);
	}
}

Post-incrementing (horses++) the above would output 4 because it’s outputting before it’s incrementing, in other words, it changed the variable after it outputted it.

Take this example;

class jamesprogram {

	public static void main(String args[]){
			
		int horses=4;
		horses = horses +6;

			
		System.out.println(horses++);
	}
}

The line
horses = horses +6;

can be replaced with
horses +=6;

for the same result.

Leave a Reply