Exercise 4-2: (1) Create a class containing a float and use it to demonstrate aliasing.
import static java.lang.System.out;
class Tank
{
float level;
}
public class Assignment
{
static void println(Object obj) {out.println(obj);}
public static void main(String[] args)
{
Tank t1 = new Tank();
Tank t2 = new Tank();
// t1.level = 9; // int to float OK, no precision loss
t1.level = 9.0f; // 9.0 is implicitly double (compile error)
t2.level = 47.0f;
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t1.level = t2.level; // not aliasing the fields
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t1.level = 27.0f;
t2.level = 57.0f;
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t1 = t2; // aliasing objects
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t1.level = 27.0f;
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t2.level = 57.0f;
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
}
}
/*
javac Assignment.java
java Assignment
t1.level: 9.0, t2.level: 47.0
t1.level: 47.0, t2.level: 47.0
t1.level: 27.0, t2.level: 57.0
t1.level: 57.0, t2.level: 57.0
t1.level: 27.0, t2.level: 27.0
t1.level: 57.0, t2.level: 57.0
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
Exercise 4-3: (1) Create a class containing a float and use it to demonstrate aliasing during method calls.
import static java.lang.System.out;
class Tank
{
float level;
}
// aliasing during method call (pass arguments by reference)
public class Aliasing
{
static void println(Object obj) {out.println(obj);}
static void changeLevel(Tank t, float newLevel) {t.level = newLevel;}
public static void main(String[] args)
{
Tank t = new Tank();
println("t.level: " + t.level); // initialized to 0.0f (float)
t.level = 9; // int to float OK, no precision loss
println("t.level: " + t.level); // 9.0f (printed 9.0)
// changeLevel(t, 27.0); // compile error, precision loss (from double)
changeLevel(t, 27.0f); // f for float, aliasing (t sent by reference)
println("t.level: " + t.level); // 27.0
}
}
/*
javac Aliasing.java
java Aliasing
t.level: 0.0
t.level: 9.0
t.level: 27.0
*/