Jul 04 2009

The Difference between ++x and x++

Category: Javaadmin @ 12:04 am

public class PrePostDemo
{
	public static void main(String[] args)
		{
		int a = 4;
		int b = 4;
 
		System.out.println(a);
		a++;
		System.out.println(a);
		a++;
		System.out.println(a++);
 
		System.out.println(b);
		++b;
		System.out.println(b);
		++b;
		System.out.println(++b);
		}
}

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code a++; and ++b; will both end in result being incremented by one. The only difference is that the prefix version (++b) evaluates to the incremented value, whereas the postfix version (a++) evaluates to the original value.

Tags: , ,


Jul 03 2009

The Unary Operators

Category: Javaadmin @ 11:51 pm
+ 	Unary plus operator; indicates positive value (numbers are positive without this, however)
- 	Unary minus operator; negates an expression
++  	Increment operator; increments a value by 1
--    	Decrement operator; decrements a value by 1
!     	Logical complement operator; inverts the value of a boolean
    public class UnaryDemo
    {
    	public static void main (String[] args)
    	{
     
    	int x = 3;
    	System.out.println(x);
    	x=x+5 ;
    	System.out.println(x);
    	x++ ;
    	System.out.println(x);
    	--x ;
    	System.out.println(x);
    	boolean y = true ;
    	System.out.println(y);
    	System.out.println(!y);
    	}
     
    }

    Tags: ,