Salta al contenuto
Note per Studenti Java - MyComplex, Methods and Redirection Report

Java - MyComplex, Methods and Redirection

In questa pagina 5

Continues Java - Classes, Objects and ScannerIn Java a class defines instance variables (usually private), a constructor and methods; objects are created with new and used through reference variables. A method call p1.getDistanceFrom(p2) has an implicit argument (the object p1, available inside the method as this) and explicit arguments (p2). Arguments are always passed by value: a copy of the value or of the reference is passed. Comparing references with == tests whether they point to the same object, while equals() compares the content; null is tested with ==; floating point numbers are compared with a tolerance. Public methods are documented with javadoc comments (param, return). The Scanner class splits a string or the standard input into tokens with hasNext() and next() and offers hasNextInt, hasNextDouble, hasNextLine; the end of the standard input is ctrl+z then return on Windows and ctrl+d on Unix. Worked exercises: the MyPoint2D point class with its tester, and the specification of a MyComplex class.Java - Classes, Objects and Scanner →, which gives the task of the MyComplex class. Here: the complete class, the programming tips that go with it, how arguments are passed, and redirection of standard input and output. The next topic is Java - ArraysA Java array is an object holding a sequence of elements of the same type (primitive or reference). It is built with new TypeName[length], assigned to a reference variable declared TypeName[] name (no length in the declaration, so the variable can later refer to arrays of any length). Elements start at 0, false or null; they are read and written with name[index], with index from 0 to length - 1; any other index throws ArrayIndexOutOfBoundsException at run time (typical bug: index equal to length, or i <= values.length in a loop). The size is the public final variable length (not a method, cannot be assigned). Elements can be given at once with {2, 3, 5}. Assigning an array variable to another copies only the reference (both see the same array); a real copy needs a new array of the same type and length filled by a loop or by System.arraycopy(from, fromStart, to, toStart, count).Java - Arrays →. Compare the idea of functions in Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files →.

1. Exercise: complex numbers (MyComplex), the full class

Two private instance variables hold the real and imaginary parts; every method is documented with javadoc comments (see Java - Classes, Objects and ScannerIn Java a class defines instance variables (usually private), a constructor and methods; objects are created with new and used through reference variables. A method call p1.getDistanceFrom(p2) has an implicit argument (the object p1, available inside the method as this) and explicit arguments (p2). Arguments are always passed by value: a copy of the value or of the reference is passed. Comparing references with == tests whether they point to the same object, while equals() compares the content; null is tested with ==; floating point numbers are compared with a tolerance. Public methods are documented with javadoc comments (param, return). The Scanner class splits a string or the standard input into tokens with hasNext() and next() and offers hasNextInt, hasNextDouble, hasNextLine; the end of the standard input is ctrl+z then return on Windows and ctrl+d on Unix. Worked exercises: the MyPoint2D point class with its tester, and the specification of a MyComplex class.Java - Classes, Objects and Scanner →).

java
/**
 * MyComplex
 * Implements complex numbers
 * @author ...
 * @version ...
 */
public class MyComplex
{  // private section
   private double re; // real part
   private double im; // imaginary part

   /**
      Initializes this complex number to the value re + i*im
      @param re real part
      @param im imaginary part
   */
   public MyComplex(double re, double im) // it's bad style to give the same names
   {  this.re = re;                       // to the constructor arguments and instance variables
      this.im = im;
      /* by using the this reference we can solve the ambiguity
         It is a best style to use different names for the arguments and the instance variables
         For example: double real; double immag; or double aRe; double anIm */
   }

   /**
      Initializes this complex number to the value re + i0
      @param re real part
   */
   public MyComplex(double re)
   {  this(re, 0); /* strange statement! In alternative we can simply write
                      this.re = re; this.im = 0; */
   }

   /**
      Initializes the complex number 0 + i0 (complex zero)
   */
   public MyComplex()
   {  this(0);
   }

   /**
      sums this complex number with the specified one
      @param z specified complex number
      @return the sum of this complex number and the specified one (this + z)
   */
   public MyComplex add(MyComplex z)
   {  return new MyComplex(re + z.re, im + z.im);
   }

   /**
      sums the specified complex numbers - static method
      @param z1 first specified complex number
      @param z2 second specified complex number
      @return the sum of the first and second specified numbers (Z1 + Z2)
   */
   public static MyComplex add(MyComplex z1, MyComplex z2)
   {  return new MyComplex(z1.re + z2.re, z1.im + z2.im);
   }

   /**
      Subtracts the specified complex number from this complex number
      @param z specified complex number
      @return the complex number resulting from the subtraction (this - z)
   */
   public MyComplex sub(MyComplex z)
   {  return new MyComplex(re - z.re, im - z.im);
   }

   /**
      multiplies this complex number by the specified complex number
      @param z specified complex number
      @return complex number resulting from the product (this * z)
   */
   public MyComplex mult(MyComplex z)
   {  return new MyComplex(re * z.re - im * z.im, re * z.im + im * z.re);
   }

   /**
      divides this complex number by the specified complex number
      @param z specified complex number
      @return the complex number resulting from the division (this / z)
   */
   public MyComplex div(MyComplex z)
   {  return mult(z.inv());
   }

   /**
      computes the reciprocal of this complex number
      @return the reciprocal of this complex number (1/z)
   */
   public MyComplex inv()
   {  return new MyComplex(re / (mod() * mod()), -im / (mod() * mod()));
   }

   /**
      computes the complex conjugate of this complex number
      @return the complex conjugate of this complex number
   */
   public MyComplex conj()
   {  return new MyComplex(re, -im);
   }

   /**
      Computes the modulus of this complex number
      @return modulus of this complex number |this|
   */
   public double mod()
   {  return Math.sqrt(re * re + im * im);
   }

   /**
      Returns the real part of this complex number
      @return real part of this complex number
   */
   public double re()
   {  return re;
   }

   /**
      Returns the imaginary part of this complex number
      @return imaginary part of this complex number
   */
   public double im()
   {  return im;
   }

   /**
      returns the textual description of this complex number in the format MyComplex x +iy
      (Example: "MyComplex 1 +i9" or "MyComplex 2 -i7")
   */
   public String toString()
   {  final String IMAGINARY_UNIT = "i";

      if (equalsApprox(im, 0))
         return String.valueOf(re);

      String sign = "-";
      if (im > 0)
         sign = "+";

      if (equalsApprox(re, 0))
         return "MyComplex " + sign + IMAGINARY_UNIT + Math.abs(im);

      return "MyComplex " + re + " " + sign + IMAGINARY_UNIT + Math.abs(im);
   }

   /**
      compares with tolerance this complex number and the specified complex number. The numbers
      are considered identical if both real and imaginary parts are equals with tolerance
      @return true if this complex number and the specified one are identical with tolerance,
              false otherwise
   */
   public boolean equalsApprox(MyComplex z)
   {  return equalsApprox(re, z.re) && equalsApprox(im, z.im);
   }

   /*
      private method to compare with tolerance two double numbers
      It is defined private because it is used only within this class
      It is defined static because it processes only the arguments
      Note: no javadoc-style comments are used for private methods
   */
   private static boolean equalsApprox(double x, double y)
   {  final double EPSILON = 1E-14; // tolerance

      return Math.abs(x - y) <= EPSILON *
             Math.max(Math.abs(x), Math.abs(y));
   }
} // end of the class

Points to remember about this listing:

1.1 The test class

Write a simple test class that reads two complex numbers from standard input and prints on standard output:

  • the textual description of the two numbers;
  • their sum, subtraction, product and division;
  • the inverse, the modulus, the real and imaginary parts.

Then identify test cases. (The slide gives only the specification, no solution.)

2. Programming classes: useful tips

2.1 Names of the constructor arguments

java
private double re; // instance variable
private double im; // instance variable
public MyComplex(double re, double im)
{  re = re;     // ERROR!
   im = im;
}

The compiler cannot tell whether re and im are instance variables or method arguments (the arguments hide the instance variables, so these assignments do not set the object's variables). Two ways out:

java
public MyComplex(double re, double im)
{  this.re = re;   // OK: the implicit argument this solves the ambiguity
   this.im = im;
}
java
public MyComplex(double aRe, double anIm)
{  re = aRe;       // OK: best programming style
   im = anIm;
}

2.2 Calling a constructor from another constructor

java
public MyComplex(double aRe, double anIm)
{  re = aRe;
   im = anIm;
}

public MyComplex(double aRe) // initializes the number re+i0
{  this(aRe, 0.0);   // call to constructor MyComplex(double aRe, double anIm)
}

public MyComplex()  // initializes the number 0+i0
{  this(0.0);        // call to constructor MyComplex(double unRe)
}
  • The call to this(...) must be the first statement of the constructor.
  • Advantage: code reuse.

2.3 Methods that return a new object

java
private double re; // instance variable
private double im; // instance variable
...
/**
   Computes the sum this + z (this implicit argument)
   @return complex number this + z
*/
public MyComplex add(MyComplex z)   // returns a data item of type MyComplex; argument of type MyComplex
{  MyComplex c = new MyComplex(re + z.re, im + z.im);
   return c; // c temporary variable
}

The temporary variable is not needed; the more concise form is also OK:

java
public MyComplex add(MyComplex z) // more concise expression
{  return new MyComplex(re + z.re, im + z.im);
}

Usage of instance variables. In re + z.re, im + z.im, re and im are the instance variables of the implicit argument (this.re, this.im), z.re and z.im those of the explicit argument. The private variables of another MyComplex instance z are accessed with the notation z.re or z.im only in the methods of the class itself.

Access to the instance variables in non-static methods. For the call

java
// method belonging to another class
MyComplex a = new MyComplex(1,2);
MyComplex b = new MyComplex(2,3);
MyComplex c = a.add(b);

inside add, this is a (so re means this.re, im means this.im) and z is b.

2.4 Textual description: toString

The toString() method returns a string with a textual description of the object's state.

java
public String toString()   // returns a string
{  char sign = '+';
   if (im < 0)
      sign = '-';
   return "MyComplex " + re + " " + sign + " i" + Math.abs(im);
}

What is it for? For example to print the value of an object. These two have the same effect and print MyComplex 1 - i2:

java
MyComplex z = new MyComplex(1,-2);
System.out.println(z.toString());
java
MyComplex z = new MyComplex(1,-2);
System.out.println(z);

(println of an object uses its toString().)

2.5 Accessor and modifier methods, immutable classes

  • The methods of MyComplex access the internal state of the objects (instance variables) without ever modifying it: they are accessor (access) methods, like conj().
  • Other classes have methods that modify the state of objects: modifier methods, like deposit of BankAccount.
java
// Class MyComplex                       ACCESS METHOD
public MyComplex conj()
{  return new MyComplex(re, -im);
}
java
// Class BankAccount                     MODIFIER METHOD
public void deposit(double amount)
{  balance += amount;
}

Recommendation: give modifier methods a return value of void.

IMMUTABLE classesclasses that have only access methods: MyComplex is immutable, and so is java.lang.String. References to objects of immutable classes can be distributed and used without fear of altering the information contained in the objects themselves; not so for objects of non-immutable classes.

2.6 Boolean methods

Boolean methods are methods that return a boolean value. Example: compare two complex numbers. The first form is the best programming style; the other two are OK:

java
public boolean equalsApprox(MyComplex z)
{  return equalsApprox(re, z.re) && equalsApprox(im, z.im);
}
java
public boolean equalsApprox(MyComplex z)
{  if (equalsApprox(re, z.re) && equalsApprox(im, z.im))
      return true;
   else return false;
}
java
public boolean equalsApprox(MyComplex z)
{  if (equalsApprox(re, z.re) && equalsApprox(im, z.im))
      return true;
   return false;
}

2.7 Private methods

  • Private methods can be programmed inside classes and can be invoked only within the methods of the class itself.
  • Use them to isolate a precise function that is typically called several times in the code.
  • Example: two complex numbers are compared by admitting a tolerance on the real and imaginary parts (they are double numbers), as in equalsApprox of section 1.
java
public boolean equalsApprox(MyComplex z)
{  return equalsApprox(re, z.re) && equalsApprox(im, z.im);
}
private static boolean equalsApprox(double x, double y)
{  final double EPSILON = 1E-14; // tolerance
   return Math.abs(x - y) <= EPSILON * Math.max(Math.abs(x), Math.abs(y));
}

2.8 Instance methods and static methods

  • Instance methods process the instance variables and the explicit arguments.
  • Static methods process only the explicit arguments (and static variables, which come later).
java
public class MyComplex
{ ...
  // instance method (uses instance variables)
  public MyComplex add(MyComplex z)
  {  return new MyComplex(re + z.re, im + z.im);
  }
  // static method (cannot use instance variables)
  public static MyComplex add(MyComplex z1, MyComplex z2)
  {  return new MyComplex(z1.re + z2.re, z1.im + z2.im);
  }
  ...
}

Calls from another class:

java
public class OtherClass
{ ...
  MyComplex c1 = new MyComplex(1, 2);
  MyComplex c2 = new MyComplex(2, 3);
  ...
  // call to the instance method add()
  MyComplex s1 = c1.add(c2);
  ...
  // call to the static method add()
  MyComplex s2 = MyComplex.add(c1, c2);
}

The instance method is called on an object (c1.add(c2)), the static one on the class name (MyComplex.add(c1, c2)). Both give the same sum.

2.9 Never overwrite arguments

The arguments of a method are variables in all respects, so you can assign a new value to them. Don't.

java
public void deposit(double amount)
{  amount = balance + amount;   // STOP
   ...

After the assignment, amount no longer holds the value of the actual argument passed to the method. This is the source of many errors, especially in the code maintenance phase. Better:

java
public void deposit(double amount)
{  double tmpB = balance + amount;
   ...

Rule: never change the argument values of a method; use an additional local variable instead.

2.10 Common error: a troublesome semicolon

Do not insert by mistake a ; after if, for and while statements.

java
int n = 10;
for (int i = 0; i < n; i++); // ahi!!!!
   System.out.println(i + " ");

The compiler reads it as

java
int n = 10;
for (int i = 0; i < n; i++)
   ;  // empty statement: does nothing!
System.out.println(i + " ");

The loop does nothing for i from 0 to 9 and then prints i. Here i is declared in the for and is not defined in the System.out.println(...) statement, so the compiler reports the error:

C:\javaExamples>javac TestSemicolon.java
TestSemicolon.java:6: cannot find symbol
symbol  : variable i
location: class TestSemicolon
        System.out.println(i + " ");
                           ^
1 error

If the variable is defined outside the loop:

java
int n = 10;
int i;
for (i = 0; i < n; i++); //ahi!
   System.out.println(i + " ");

the compiler reports no error, but at run time the code prints only 10, the value of i at the end of the loop. This is worse: a silent logic error.

3. Passing arguments to methods

3.1 Formal and actual arguments

  • The explicit arguments in the method signature and the implicit argument this (used within the methods) are the formal argumentsthe arguments that appear in the method signature plus the implicit argument this of the method.
  • The actual argumentsthe arguments used in the method invocation are the ones used in the invocation.
  • At the time of invocation, the actual arguments are copied to the formal arguments.
java
public MyComplex add(MyComplex z)
{  return new MyComplex(this.re + z.re, this.im + z.im);
}
java
MyComplex a = new MyComplex(1,2);
MyComplex b = new MyComplex(2,3);
MyComplex c = a.add(b);   // a is copied to this, b is copied to z

3.2 Numeric arguments cannot be modified

An increment() method providing a new value for a numeric variable:

java
// it is used as x = increment1(x)
public static int increment1(int index)
{  return index + 1;
} // is equivalent to a x++

Why not a void static method that changes the argument?

java
// it is used as increment2(x)
public static void increment2(int index)
{  index = index + 1;
} // FAILS TO MODIFY X!
java
int n = 1;
increment2(n);
System.out.println("n =" + n);   // n = 1

When the method is called, the value of n is copied to index; index goes from 1 to 2 inside increment2, but the value of n is unchanged.

3.3 Object arguments: modify the state, not the reference

A method can modify the state of an object passed as an argument:

java
// class BankAccount
// transfers money from bank account this to bank account to
public void transfer(BankAccount to, double amount)
{  withdraw(amount);          // withdraws from this bank account
   to.deposit(amount);        // deposit to the other bank account
} // IT WORKS!

but it cannot modify the reference contained in an actual argument:

java
// IT DOES NOT WORK!
public static void swapAccounts(BankAccount x, BankAccount y)
{  BankAccount temp = x;
   x = y;
   y = temp;
}

After swapAccounts(a, b); the variables a and b remain unchanged: only the copies x and y of the references are swapped.

3.4 Everything is passed by value

  • In Java the passing of arguments is done "by value": the value of the actual argument is copied to the formal argument. This prevents the modification of the value contained in the variable used as actual argument.
  • Other languages (such as C++) allow other mechanisms, for example "by reference", which makes it possible to modify the actual arguments.
  • It is said, improperly, that in Java numbers are passed by value and objects by reference. Actually all variables are passed by value; but passing an object variable by value you pass a copy of the reference it contains.
  • The practical effect of passing a reference by value is the ability to change the state of the object itself, as it happens with passing "by reference".

4. Standard input and output redirection

4.1 Standard input

The program SumD computes the sum of a sequence of numbers:

java
import java.util.Scanner;
public class SumD
{  public static void main(String[] args)
   {  Scanner in = new Scanner(System.in);

      double sum = 0;
      while (in.hasNextDouble()) {
         sum = sum + in.nextDouble();
      }
      System.out.println("Sum: " + sum);

      in.close();
   }
}

The numbers are typed at the terminal and not stored in a list: to add up a series of numbers you have to type them all, but there is no trace of them. A logical solution is for the program to read the numbers from a file, which is done with the standard input redirection, provided by almost all operating systems.

Redirection of standard input, in both Unix and MS Windows, is written with < followed by the name of the file from which to receive the input data:

$ java SumD < input.txt

The file (input.txt) is connected to the standard input. The program needs no special instruction: simply System.in is no longer connected to the terminal but to the specified file (so hasNextDouble() becomes false at the end of the file).

4.2 Standard output

Redirecting the standard output is convenient, for example, when the program produces many lines of output that would scroll quickly across the screen:

java Sum > output.txt
  • If output.txt does not exist it is created; if it exists it is overwritten.
  • To not overwrite the file, use >>:
java Sum >> output.txt
  • Input and output redirection can be combined:
java Sum < input.txt > output.txt

Exam checklist

  • Constructor argument with the same name as an instance variable: use this.re = re (or different names, best style). this(...) to call another constructor must be the first statement.
  • new MyComplex(...) returned by add, sub, mult, div, inv, conj: the operands are not modified (immutable class).
  • div(z) is mult(z.inv()); inv is re/mod^2, -im/mod^2; mod is Math.sqrt(re*re + im*im).
  • Doubles are compared with a tolerance: Math.abs(x - y) <= EPSILON * Math.max(Math.abs(x), Math.abs(y)); the helper is private static.
  • Instance method: on an object, uses this; static method: on the class name, only explicit arguments.
  • Java passes by value always: a method cannot change a caller's number or make the caller's reference point elsewhere (increment2, swapAccounts), but it can change the state of the object a reference points to (transfer).
  • Never assign to a method argument; use a local variable.
  • A ; right after for (...), if (...), while (...) is an empty body: wrong behaviour or "cannot find symbol".
  • < redirects standard input from a file, > redirects output (overwrites), >> appends.

Versione ripasso

The class MyComplex (immutable)

  • Private instance variables re and im (both double). Methods return new objects or values and never change the state.
  • Constructors: (re, im), (re) with imaginary part 0, and () for zero. The shorter ones call the first with this(...), which must be the first statement.
  • Arithmetic: add, sub, mult, div(z) = mult(z.inv()), inv = (re, -im) divided by the squared modulus, conj, mod = Math.sqrt(re * re + im * im).
  • Accessors re() and im(). toString has three cases: imaginary part zero, real part zero, or both.
  • Tolerance comparison: Math.abs(x - y) <= EPSILON * Math.max(Math.abs(x), Math.abs(y)) with EPSILON = 1E-14, in a private static helper used by equalsApprox.

Essential code

java
public MyComplex(double aRe, double anIm) { re = aRe; im = anIm; }   // or this.re = re
public MyComplex(double aRe) { this(aRe, 0.0); }
public MyComplex add(MyComplex z) { return new MyComplex(re + z.re, im + z.im); }             // instance: a.add(b)
public static MyComplex add(MyComplex z1, MyComplex z2) { return new MyComplex(z1.re + z2.re, z1.im + z2.im); }  // static: MyComplex.add(a, b)
public MyComplex div(MyComplex z) { return mult(z.inv()); }

Methods and arguments

  • Accessor methods return a value without changing the state (conj); modifier methods change it and should return void (deposit).
  • Instance methods use this and the instance variables; static methods use only their explicit arguments; private methods are callable only inside the class.
  • Java passes everything by value: the actual argument is copied to the formal one.
  • A void method cannot change a caller's number (increment2(n) leaves n unchanged). Use n = increment1(n) instead.
  • A method can change the state of an object it receives (transfer), but swapping references inside a method (swapAccounts) changes only the copies.
  • Never assign to an argument: use a local variable such as double tmpB = balance + amount;.

Redirection

Common mistakes

  • re = re; in a constructor: the arguments hide the instance variables. Use this.re = re or different names.
  • A ; right after for, if or while: empty body. With a loop variable declared in the for, it gives "cannot find symbol"; with an outer variable it runs silently and prints only the final value.
  • Comparing double values without the tolerance helper.
  • Calling div, add or mult expecting the operand to change: the class is immutable.

Teoria collegata