Variables & Assignment


Variables & Assignment


Example #1

    int value1;         // Create an integer variable
    value1 = 2;         // Initialize its value to 2

    int value2 = 8;     // Create a variable initialized to 8

    int sum1 = value1 + value2;     // Set a variable to a calculated value
    System.out.println(value1 + ", " + value2 + ", " + sum1);
Output:
    2, 8, 10

Example #2

    double pi = 3.14159;
    double sum2 = pi + value2;    // int value2 will be temporarily "upgraded" to a double
    System.out.println(pi + ", " + value2 + ", " + sum2);
Output:
    3.14159, 8, 11.14159 

Example #3

    String word1 = "Hello";
    String word2 = "world";
    String greeting = word1 + " " + word2 + "!";
    System.out.println(word1 + "\n" + word2 + "\n" + greeting);

    greeting = word1 + " all!";
    System.out.println(greeting);
Output:
    Hello
    world
    Hello world!
    Hello all! 

Example #4

    double x = 5;
    double y = 10;

    double sum = x + y;
    double avg = sum / 2.0;

    System.out.println("x + y = " + sum + "; avg = " + avg);

    x = 32;
    y = 10;

    sum = x + y;
    avg = sum / 2.0;

    System.out.println("x + y = " + sum + "; avg = " + avg);
Output:
    x + y = 15; avg = 7.5
    x + y = 42; avg = 21

Alyce Brady, Kalamazoo College