Operators and Precedence

The assignment statement and arithmetic expressions

Example 8: Here are some variable declarations and assignment statements.
  int x;
  double d,d2; 
  char ch; 
  boolean found; 
  String name; 
  x = 3;   // stores 3 in location x 
  d = 3.5;  // stores 3.5 in d 
  d2 = d + 1.5;  // stores 5.0 in d2 
  d = d + d2;   // stores 3.5 + 5.0 in d, the previous value is lost 
  ch = 'J';   // stores the character J in ch 
  found = true;  // (note: NO quotes)  stores true in found 
  name = "Alice";   // stores a reference to Alice in name
Expressions involving strings Exercise 11: If x = 4.5 and y = 5.2, what are the values of the following the expressions?
   "The value of " + x + "*" + y + " is " + x * y;
   "The value of " + x + "+" + y + " is " + x + y;
   "The value of " + x + "+" + y + " is " + (x + y);
Ans: The + operator in this example is evaluated from left to right. In the first example, the * was evaluated first and then the + operator was evaluated left to right. Use parentheses to force the order that you want:
   The value of 4.5*5.2 is 23.4
   The value of 4.5+5.2 is 4.55.2
   The value of 4.5+5.2 is 9.7

The arithmetic operators:

Symbol Meaning Example
* multiplication 3 * 5 * x
/ division 5.2/1.5
% mod/remainder 7%2
+ addition 12 + x
- subtraction 35 - y

Operator precedence: The following rules are used for evaluating arithmetic expressions in Java:

Numeric data conversion: In Java, conversions can occur in three ways.

  1. Assignment conversion (the value of the expression on the right has to be converted to agree with the type of variable on the left).

  2. Arithmetic promotion (the operands of an operation need to be in the same format before the operation can be performed).
  3. Explicit casting for type conversion
Example 9: Here are some assignment statements for variables of primitive type.
   int i;
   double d;
   char ch;
   i = 3; 
   d = i; // stores a copy of i in d  (promotion in assignment)
   i = 'A'; // stores the numeric value of A (65) in i 

Example 10: In 8.0 * 5 the 5 is converted/promoted to a double before the multiplication, resulting in the value 40.0 rather than 40. Watch out for precedence: the expression (40.0 - 32.0)* (5/9) evaluates to 0.0.

Example 11: Explicit type conversion uses parentheses.
   int n = 20; 
   int d = 8; 
   double ans; 
   ans = n/d;  // 2.0 is stored in ans
   ans = (double)n/d; // 2.5 is stored in ans