Simple calculations

exercise No. 2

Working with variables

Q:

This exercise is about two variables a and b representing values being subject to change. Embed the following snippet in a class and execute the beast:

public static void main(String[] args) {

  int a = 4,
      b = 7;

  System.out.println("a=" + a);
  System.out.println("b=" + b);

  int sum = a + b;
  System.out.println("Sum: " + sum);
}
  1. Modify these values and code more sophisticated expressions.

  2. Complete the following still empty println(...) statement to create the expected output:

    Source code Expected output
    int a = 4,
        b = 7;
    
    System.out.println(...); // TODO
    4+7=11

    Your code is expected to produce correct output irrespective of the two variables a and b's values:

    Source code Expected output
    int a = -4,  // Changing just values
        b = 100;
    
    System.out.println(...); // Remains unchanged
    -4+100=96

    Tip

    Java does not only provide an arithmetic + operator: You have already seen the + operator connecting two strings. Java extends this concept of string concatenation to non-string values as well.

A:

A naive solution reads:

int a = -4,
    b = 100;

System.out.println(a + "+" + b + "=" + a + b);

This unfortunately does not work. The above expression is being evaluated from left to right thus being fully equivalent to:

System.out.println(((((a + "+") + b) + "=") + a) + b);
//                      \  /      /      /   /    / 
//                      "-4+"    /      /   /    / 
//                         \    /      /   /    /  
//                       "-4+100"     /   /    /  
//                            \      /   /    /  
//                           "-4+100="  /    / 
//                               \     /    /  
//                            "-4+100=-4"  / 
//                                  \     / 
//                              "-4+100=-4100"

As we shall see in the section called “Operators and expressions” each of these constituents evaluates to a string thus producing:

-4+100=-4100

Adding a pair of braces grouping (a+b) forces an arithmetic + operation:

Source code Output
int a = -4,
    b = 100;

System.out.println(a + "+" + b + "=" + (a + b));
-4+100=96

This is equivalent to:

System.out.println((((a + "+") + b) + "=") + (a + b));
//                     \  /     /     /        \ / 
//                     "-4+"   /     /         96    
//                        \   /     /         /  
//                     "-4+100"    /         /  
//                          \     /         /  
//                         "-4+100="       /   
//                              \         /  
//                              "-4+100=96"

Reverting to the original variable values 4 and 7 still yields a correct output:

Source code Output
int a = 4,
    b = 7;

System.out.println(a + "+" + b+ "=" + (a + b));
4+7=11