Java Tutorial/Operators/Increment Decrement Operators — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 04:57, 1 июня 2010

Increment and Decrement: Demonstrate ++.

public class MainClass {
  public static void main(String args[]) {
    int a = 1;
    int b = 2;
    int c;
    int d;
    c = ++b;
    d = a++;
    c++;
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);
    System.out.println("d = " + d);
  }
}



a = 2
b = 3
c = 4
d = 1


The increment and decrement operators

  1. add an integer variable by one.
  2. increment operator: two successive plus signs, ++.
  3. decrement operator: --.



public class MainClass {
  public static void main(String[] argv) {
    int count = 10;
    ++count;      // Add 1 to count
    --count;      // Subtract 1 from count
    
    System.out.println(count);
  }
}



10


The prefix form and the postfix form

public class MainClass {
  public static void main(String[] args) {
    int numA = 5;
    int numB = 10;
    int numC = 0;
    numC = ++numA + numB;
    System.out.println(numA);
    System.out.println(numC);
  }
}



4
14


Using ++ and -- with floating-point variables

public class MainClass{
  public static void main(String[] arg){
     double a = 12.12;
     
     System.out.println( a-- );
     System.out.println( a++ );
     System.out.println( --a );
     System.out.println( ++a );
  }
}



12.12
11.12
11.12
12.12


Using the increment and decrement operators in an expression

public class MainClass {
  public static void main(String[] args) {
    int numA = 5;
    int numB = 10;
    int numC = 0;
    numC = ++numA + numB;
    
    System.out.println(numA);
    System.out.println(numC);
  }
}



6
16