Variables
Variables are convenient handles for accessing memory. We don't need to mess with memory addresses:
Declaring a variable requires a type name like double and an
                   identifier:
            
|  | 
| {type name} {variable name} ; | 
We may assign values to variables or build expressions like pi * 2.0 * 2.0 :
            
double pi;      // Variable declaration
pi = 3.1415926; // Assigning value to variable
// Print a circle's area of radius 2.0
System.out.println(pi * 2.0 * 2.0);- Separate declaration and initialization
- double pi; // Declaration of variable pi pi = 3.1415926; // Value assignment
- Combined declaration and initialization
- double pi = 3.1415926;
| Separate declarations | Equivalent compound declaration | 
|---|---|
|  |  | 
 No. 10
               
The sum of two values
| Q: | We consider: Extend this snippet by adding a suitable  45 + 10 = 55 When changing just the values of  int i = <your first value>, j = <your second value>; System.out.println(...) | ||||
| A: | This exercise is surprisingly tricky. A naive approach might read: This unfortunately generates an erroneous outcome: 45 + 10 = 4510 The “+” operator acts from left to right doing
                                             string concatenation rather than usual arithmetics: Both int
                                             values 45 and 10 are being transformed into strings
                                              Overcoming this problem we require an additional pair of braces for partly overriding the evaluation precedence: 
 | 
| Identifier rules | Legal | Illegal | 
|---|---|---|
| 
 | 
 | 
 | 
abstract char else if long return this while assert class enum goto native short throw _ (underscore) boolean const extends implements new static throws break continue final import package strictfp transient byte default finally instanceof private super try case do float int protected switch void catch double for interface public synchronized volatile
Reserved boolean and null literal values
true false null
exports non-sealed opens provides requires to uses when yield module open permits record sealed transitive var with
- 
                           Start with a small letter like africarather thanAfrica.
- 
                           Use “camel case” e.g. myFirstCode.
- 
                           Do not start with _or$.
 No. 11
               
Legal variable names
| Q: | Which of the following names are legal variable names? If so, would you actually use them in your code? Complete the following table and explain your decision with respect to the “Language Fundamentals” / “variables” section of [Kurniawan] . 
 TipYou may want to prepare a simple Java™ program testing the above names. | ||||||||||||||||||||||||||||||||||||||||||
| A: | Consider: Unfortunately this message does not explain the underlying cause: It does not hint towards an illegal identifier name. One indication of a sound compiler implementation is its ability to provide meaningful, self explanatory error messages: 
 | 
Modifier final prohibits
                           changes:
                  
final double PI = 3.1415926;
...
PI = 1.0; // Compile time error: Constant cannot be modifiedNote
final variables by convention are
                                being capitalized
                     
Variable names are case sensitive:
int count = 32; int Count = 44; System.out.println(count + ":" + Count);
Resulting output:
32:44
int i = 2;
int j = i;   // o.K.: Assigning int to int
long l = i;  // o.K.: Widening conversion
i = l;       // Wrong: Narrowing
boolean b = true;
i = b;       // Error: int and boolean are incompatible types
i = 4.3345   // Error: Cannot assign double to int
i = "Hello"; // Even worse: Assigning a String to an int|  | Performing static range check | 
|  | No static check on  | 
 No. 12
               
Benefits of final 
               | Q: | We reconsider our code from Figure 81, “Compile time analysis ”: Adding the  Why does adding a  TipRead Static program analysis. | ||
| A: | Modifying variable  
 The  | 
var count = 30; // o.K., type can be inferred from int literal
        
var index;      // Wrong: No way to infer type here.
index = 3;| long l = 4345; int i = (int) l; // Casting long to int System.out.println("i carrying long: " + i); double d = 44.2323; i = (int) d; // Casting double to int System.out.println("i carrying double: " + i); | i carrying long: 4345 i carrying double: 44 | 
| long l = 3000000000000000L; int i = (int) l; System.out.println("i carrying long:" + i); double d = 44300000000000.0; i = (int) d; System.out.println("i carrying double:" + i); | i carrying long:-296517632 i carrying double:2147483647 | 
| double measurement = 65234.5435;
/* A cast forcing double to short conversion */
short velocity = (short) measurement;
System.out.println("Velocity = " + velocity); | Uups: Velocity = -302 | 
|  | Uups: Velocity = -302 | 
|  | 
 | 
The cause of the failure was a software error in the inertial reference system.
Specifically, a 64 bit floating point number relating to the horizontal velocity of the rocket with respect to the platform was converted to a 16 bit signed integer.
The number was larger than 32,767, the largest integer possible in a 16 bit signed integer, and thus the conversion failed.
Related video explanation
 No. 13
               
«C» vs. Java.
| Q: | We reconsider the «C» code example from Figure 87, “«C» programming language “liberal” assignment policy: ”: Rewrite the same code in Java. Replace  
 | ||||
| A: | 
 | 
 No. 14
               
Assignment and type safety
| Q: | We consider: This snippet shows correct Java™ code.
                                          However Figure 80, “Type safety ” suggests we should
                                          not be allowed to assign an  Even worse: Swapping types yields a compile time error: Questions to answer: 
 | ||||
| A: | 
 Caveats using explicit casts: 
 | 
Java™ provides meta information on types:
 No. 15
               
An int's minimum and
                        maximum value 
               | Q: | In this exercise we look at an  A Java™  Java™ implements negative values using Two's complement representation. We provide some values: Table 1. 4 Byte Two's
                                                  complement representation of  intvalues.
 Use  int minimum = 0B... , //TODO: provide values by maximum = 0B...; // binary int literals System.out.println("Minimum:" + minimum); System.out.println("Maximum:" + maximum); TipYou may get some inspiration from Figure 57, “3 bit two-complement representation ” and Figure 59, “Signed 8 bit integer binary representation ”. | ||||||
| A: | We insert Two's complement
                                             representations of minimum and maximum int values according to
                                             Table 1, “4 Byte Two's
                                                  complement representation of  BTW: The JDK™ does provide maximum
                                             value, minimum value and related information for   | 
|  | 44 Jim Different | 
|  | $a + $b = 5 $jim + $a = 2 | 
//Bad!
double pi = 3.141592653589793;
...
pi = -4; // Woops, accidential and erroneous redefinition//Good
final double PI = 3.141592653589793;
...
PI = -4; // Compile time error:
         // Cannot assign a value to final variable 'pi'GpsPosition start = new GpsPosition(48.7758, 9.1829);
String name = "Simon";
LocalDate birtday = LocalDate.of(1990, Month.JULY, 5);