Java - Classes, Objects and Scanner
In questa pagina 8
Continues Java - Language BasicsJava (Sun Microsystems, 1991) is an object-oriented language designed to be simple and CPU-independent ("write once, run anywhere"). Every program is made of classes; an executable class needs a main method, and the public class name must match the file name (Hello.java). The source is compiled by javac into bytecode (Hello.class), the machine code of the Java Virtual Machine, which the Java interpreter (java Hello) runs, translating on the fly into real CPU instructions; so Java is both compiled and interpreted, portable at source and bytecode level and of intermediate efficiency. Errors are syntax (found by the compiler) or logical (found only by testing). The grammar has five token types (keywords, identifiers, literals, separators, operators). Complements: loop end tests with less-than, sentinel values and the loop and a half, break and continue, the conditional operator and switch.Java - Language Basics → (first program, compilation, grammar, loops, switch). Here: how a class is written, documented and used through the exercise of a point in the plane, how arguments are passed, how objects are compared, and how Scanner splits text into tokens and reads data. For the idea of functions and methods compare 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. Documenting the public interface: javadoc
There is a standard format for documentation comments; if used, the javadoc program automatically generates documentation in HTML.
- A documentation comment starts with
/**and ends with*/. - One must be written to describe the purpose of each non-private method.
- Tags inside the comment:
@paramfollowed by the name of the argument and its short description;@returnfollowed by a short description of the return value. - A short comment can also be written for the class:
@authorfollowed by the author's name,@versionfollowed by a version number or a date.
/**
deposits the specified amount of money into this bank account
@param amount the specified amount of money
*/
public void deposit(double amount)
/**
withdraws the specified amount of money from this bank account
@param amount the specified amount of money
*/
public void withdraw(double amount)Documentation is generated from the command line by giving the file name:
javadoc ClassName.javawhich prints messages such as Loading source file ..., Constructing Javadoc information..., Generating index-all.html... and produces a set of HTML files.
2. Exercise: a point in the Cartesian plane (MyPoint2D)
Task. Write the MyPoint2D class representing a point of the plane with two coordinates, with:
- the distance of two points (a real number): ;
- the midpoint of two points (a new point): ;
- the textual description of the object;
- a boolean method (a method returning a boolean) telling whether two points coincide: and, at the same time, .
2.1 Method signatures and the implicit argument
public double getDistanceFrom(MyPoint2D q) {...}
public MyPoint2D getMidpoint(MyPoint2D q) {...}
public boolean isCoincident(MyPoint2D q) {...}Used as:
MyPoint2D p1 = new MyPoint2D(...);
MyPoint2D p2 = new MyPoint2D(...);
double d = p1.getDistanceFrom(p2);
MyPoint2D m = p1.getMidpoint(p2);
if (p1.isCoincident(p2)) {...}p1is the implicit argument (the object on which the method is invoked);p2is the explicit argument (written in the round brackets). The explicit argument here is of reference data type (MyPoint2D).- The return type can be a primitive (
double), a reference type (MyPoint2D, a new point) orboolean.
2.2 The class
/**
* MyPoint2D
* represents a point in the Cartesian plane
*/
public class MyPoint2D
{ //instance variables
private double x; // x coordinate
private double y; // y coordinate
/**
Initializes a new point with the specified coordinates
@param aX x the specified x coordinate
@param aY y the specified y coordinate
*/
public MyPoint2D(double aX, double aY)
{ x = aX;
y = aY;
}
/**
Computes the distance between this point and the specified point
@param q the specified point
@return distance between points
*/
public double getDistanceFrom(MyPoint2D q)
{
double d2 = (x - q.x)*(x - q.x) + (y - q.y)*(y - q.y);
return Math.sqrt(d2);
}
/**
Computes the midpoint between this point and the specified point
@param q the specified point
@return midpoint
*/
public MyPoint2D getMidpoint(MyPoint2D q)
{
double xm = (x + q.x) / 2;
double ym = (y + q.y) / 2;
MyPoint2D tmp = new MyPoint2D(xm, ym);
return tmp;
}
/**
Textual description with format MyPoint2D: x, y
@return textual description
*/
public String toString()
{
return "MyPoint2D: " + x + ", " + y;
}
/**
Checks if this point and the specified point coincide
@param q the specified point
@return true if the points coincide, false otherwise
*/
public boolean isCoincident(MyPoint2D q)
{
return approxEquals(x, q.x) && approxEquals(y, q.y);
}
private boolean approxEquals(double a, double b)
{
final double EPSILON = 1E-14;
return Math.abs(a - b) <= EPSILON
* Math.max(Math.abs(a), Math.abs(b));
}
} // end of classPoints to remember:
- Instance variables
xandyareprivate: each object has its own copy. Inside the class the coordinates of another object of the same class are reached asq.x,q.y. - The constructor has the same name as the class, no return type, and initialises the instance variables (
x = aX; y = aY;). Objects are created withnew MyPoint2D(x1, y1). getMidpointbuilds and returns a new object: the original points are not modified.toString()returns the textual description in the formatMyPoint2D: x, y, built by concatenating strings and numbers with+.isCoincidentdoes not compare the coordinates with==: floating point numbers are compared with a tolerance by the private helperapproxEquals(afinalconstantEPSILON = 1E-14multiplied by the larger of the two absolute values). A private method is not part of the public interface, so it does not need a documentation comment.
2.3 The test class
The task also asks for a test class that reads two points from the standard input, computes distance and midpoint and prints them, and requires identifying test cases.
Test cases on the slide: , , , with
- and midpoint ;
- and midpoint .
/**
* MyPoint2DTester
* test class of class MyPoint2D
*/
import java.util.Scanner;
import java.util.Locale;
public class MyPoint2DTester
{ public static void main(String[] args)
{ Scanner in = new Scanner(System.in); // opens the input data stream
in.useLocale(Locale.US);
System.out.print("Enter x1 e y1 ");
double x1 = in.nextDouble();
double y1 = in.nextDouble();
System.out.print("Enter x2 e y2 ");
double x2 = in.nextDouble();
double y2 = in.nextDouble();
in.close(); // closes the input data stream
MyPoint2D p = new MyPoint2D(x1, y1); // creates new point p
MyPoint2D r = new MyPoint2D(x2, y2); // creates new point r
System.out.println("Distance of point " + p + " from point " + r
+ " is " + p.getDistanceFrom(r));
System.out.println("Midpoint of point " + p + " and point " + r
+ " is " + p.getMidpoint(r));
}
}import java.util.Scanner;makes the class available;new Scanner(System.in)opens the standard input;in.close()closes it.in.useLocale(Locale.US)sets the locale to the US one for the input;nextDouble()reads the next token as adouble.
3. Argument passing
Arguments in Java are always passed by value: when a method is invoked, a copy of each argument, whether it is a value or a reference, is passed to the method.
// method that uses MyPoint2D class
MyPoint2D p1 = new MyPoint2D(1,2);
MyPoint2D p2 = new MyPoint2D(2,3);
double d = p1.getDistanceFrom(p2); // p2: actual argument
// class MyPoint2D - method getDistanceFrom
public double getDistanceFrom(MyPoint2D q) // q: formal argument- The argument in the call is the actual argument; the parameter in the method header is the formal argument.
- Access to instance variables inside non-static methods: the reference variable
p1is copied into the implicit argumentthis, and the actual argumentp2is copied into the formal argumentq. Thenxmeansthis.xandymeansthis.y, whileq.xandq.yare the coordinates of the other point. - Since references are copied,
qandp2refer to the same object.
4. Comparison of objects
How comparison is done depends on the type:
- integers: relational operators,
if (n == 0 || n > 5); - floating point numbers: with tolerance,
final double EPSILON = 1E-14;
if (Math.abs(x - y) <=
EPSILON * Math.max(Math.abs(x), Math.abs(y)))- strings: with the methods
equals,equalsIgnoreCaseandcompareTo, for exampleif (s1.equals(s2)).
4.1 == compares references
Using == on two object references checks whether the references point to the same object.
String s1 = "MyString";
String s2 = s1;
String s3 = "MyStrin";
s3 = s3 + "g"; // s3 contains "MyString"s1 == s2is true: both point to the same object.s1 == s3is false: they point to different objects, even if both objects have the same content ("identical"). (Slide diagram:s1ands2point to oneStringobject,s3to another one with the same text.)
4.2 equals() compares the content
s1.equals(s3) is true: they point to two identical String objects.
- To check whether a reference is
nulluse the equality operator, notequals():if (s == null). equals()can be applied to any object because it is defined in theObjectclass, from which all classes derive. But each class must redefineequals()(asStringdoes): otherwise theequals()ofObjectsimply uses the equality operator. Theequals()of a class must compare the characteristics (instance variables) of its objects.- For now
equals()is used only for objects of standard library classes; objects of classes defined by us are not compared unless the methodequalsis defined in the class itself.
5. Decomposing a string into tokens with Scanner
A token is a substring with well-defined syntactic characteristics, for example delimited by spaces: in "one two three" the tokens are "one", "two", "three". Decomposing strings into tokens is a common problem. The Scanner class of the java.util package (already used to read the standard input) is very useful for it.
- By default
Scannerconsiders as delimiters spaces, tab characters, "carriage return" and "line feed": these and other characters are called whitespaces and are recognised by the boolean methodCharacter.isWhitespace(char c). - Create a
Scannerby passing the string to the constructor:
String line = "one two three";
Scanner st = new Scanner(line);- The number of tokens is generally not known in advance. Successive calls of
next()return successive tokens.next()throwsjava.util.NoSuchElementExceptionif there are no more tokens:
String token1 = st.next(); // "one"
String token2 = st.next(); // "two"
String token3 = st.next(); // "three"
String token4 = st.next(); // java.util.NoSuchElementException- So before calling
next()check with the boolean methodhasNext(), true if a subsequent token not yet extracted is present. It is ideal when the number of tokens is unknown:
while (st.hasNext())
{
String token = st.next();
...// now process token
}Trace on "one two three": the first hasNext() finds "one" and returns true, next() acquires it; then "two", then "three"; the next hasNext() finds no token left and returns false, so the loop ends. The original string remains unchanged.
- Similar boolean methods exist for each fundamental type:
hasNextInt(),hasNextDouble(),hasNextLong(), ... andhasNextLine(), useful for reading lines and used when the row structure of the data must be preserved.
6. Reading a sequence from the standard input
With an unknown number of data a sentinel value can be used (see Java - Language BasicsJava (Sun Microsystems, 1991) is an object-oriented language designed to be simple and CPU-independent ("write once, run anywhere"). Every program is made of classes; an executable class needs a main method, and the public class name must match the file name (Hello.java). The source is compiled by javac into bytecode (Hello.class), the machine code of the Java Virtual Machine, which the Java interpreter (java Hello) runs, translating on the fly into real CPU instructions; so Java is both compiled and interpreted, portable at source and bytecode level and of intermediate efficiency. Errors are syntax (found by the compiler) or logical (found only by testing). The grammar has five token types (keywords, identifiers, literals, separators, operators). Complements: loop end tests with less-than, sentinel values and the loop and a half, break and continue, the conditional operator and switch.Java - Language Basics →); the string "Q" below ends the sequence:
Scanner in = new Scanner(System.in);
int sum = 0;
boolean done = false;
while (!done)
{ String line = in.nextLine();
if (line.equalsIgnoreCase("Q"))
done = true;
else
sum += Integer.parseInt(line);
}The same hasNext() loop works on System.in:
while (st.hasNext())
{
String token = st.next();
// now we can process token
}- Here
hasNext()stops the execution and waits for data entry from the standard input. The data is acquired by the program when the operator presses the Enter key; for example typingone two threeand Enter delivers the string"one two three"to the standard input, thenhasNext()acts on it as in the string decomposition above. - At the end of data entry, the operating system is notified that the standard input for the running program is finished with a special key combination:
- DOS/Windows window: ctrl + z followed by return;
- Unix shell: ctrl + d.
When these are typed,
hasNext(), whose execution was interrupted waiting for data, returns false and the reading loop ends.
Example: counting words
import java.util.Scanner;
public class WordCounter
{
public static void main(String[] args)
{
Scanner c = new Scanner(System.in);
int count = 0;
while (c.hasNext())
{
c.next(); // extracts the token!
count++;
}
System.out.println(count + " words");
c.close();
}
}c.next() must be called inside the loop, otherwise hasNext() would always find the same token and never return false.
7. Exercise: complex numbers (MyComplex)
Java has neither a primitive data type nor a ready-to-use class in the platform API for complex numbers. The task is to write the MyComplex class implementing:
- addition, subtraction, product, division;
- real and imaginary parts, modulus, complex conjugate, reciprocal ();
- a textual description in the format "a + ib".
The slides give the signature of the sum as a method with implicit argument z1 and explicit argument z2, returning a new object:
/**
sums this complex number with the specified one
@param z the specified complex number
@return sum of the complex numbers
*/
public MyComplex add(MyComplex z) {...}
// if z1 and z2 are references to instances of the MyComplex class
MyComplex z3 = z1.add(z2);The same pattern (the method returns a new object, the operands are unchanged) applies to the other operations, as with getMidpoint in MyPoint2D.
8. Exam checklist
- Instance variables private; constructor named as the class;
newcreates objects; reference variables hold references. - In
p1.method(p2):p1is the implicit argument (thisinside the method),p2the explicit one; actual argument in the call, formal argument in the header. - Arguments are always passed by value: a copy of the value or of the reference.
==on references tests identity (same object),equals()tests content; testnullwith==;equals()must be redefined in the class, otherwise it behaves like==.- Floating point comparison: absolute difference below
EPSILONtimes the larger absolute value, never==. - javadoc:
/** ... */with@param,@return(and@author,@versionfor the class);javadoc ClassName.javamakes HTML. - Scanner on strings and on
System.in:hasNext()beforenext();NoSuchElementExceptionotherwise; end of standard input with ctrl+z and return (Windows) or ctrl+d (Unix);hasNextInt,hasNextDouble,hasNextLine.
Versione ripasso
javadoc: a /** ... */ comment before each non-private method, with @param (name and description) and @return; the class may have @author and @version. javadoc ClassName.java generates HTML.
MyPoint2D exercise
- Private instance variables
xandy; the constructor has the class name and no return type. getDistanceFrom(q)returns adouble: .getMidpoint(q)returns a new object; the original points are unchanged.toString()returnsMyPoint2D: x, y.isCoincident(q)never uses==on doubles: the privateapproxEqualschecks the difference againstEPSILON = 1E-14times the larger absolute value.- Test class: reads
x1 y1 x2 y2withScanner, prints distance and midpoint. Test cases: P(1,0), Q(0,1) gives and midpoint ; R(3,0), S(0,4) gives 5 and midpoint .
Arguments
- In
p1.getDistanceFrom(p2),p1is the implicit argument (this) andp2the explicit one (q). Inside the methodxmeansthis.x, whileq.xis the other point's coordinate. - Arguments are always passed by value: the method receives a copy of the value or of the reference. Actual argument in the call, formal argument in the header.
- Return types can be primitive, reference or
boolean.
Comparing
- Integers: relational operators. Floating point: with tolerance. Strings:
equals,equalsIgnoreCase,compareTo. ==on references tests whether they point to the same object:s1 == s3is false even with equal content.equals()compares content. It is defined inObject, but each class must redefine it, otherwise it behaves like==.- Test for
nullwith==:if (s == null).
Scanner on a string
- Default delimiters are whitespace, recognised by
Character.isWhitespace. next()returns successive tokens and throwsNoSuchElementExceptionwhen none are left; callhasNext()first.hasNextInt,hasNextDouble,hasNextLineexist too. The original string is unchanged.
Scanner on System.in
hasNext()waits for input; data arrives when Enter is pressed.- End of input: ctrl+z then return (Windows), ctrl+d (Unix). Then
hasNext()returns false. - Counting words:
next()must be called inside the loop, orhasNext()keeps finding the same token.
MyComplex exercise: Java has no complex type in its API. Implement add, subtract, product, division, real and imaginary parts, modulus, conjugate, reciprocal, and toString in the form "a + ib". Operations return new objects, as getMidpoint does.
Common mistakes: comparing strings or doubles with ==; forgetting to redefine equals(); expecting arguments to be passed by reference; calling next() without hasNext(); forgetting that hasNext() needs a next() inside the loop.