Post on 12-Apr-2017
transcript
Riccardo Rigon
Java for HydrologistsLinear Equations
R. R
igon
- Il
tav
olo
di
lavo
ro d
i R
emo w
olf
Wednesday, September 4, 13
A program must be:- short- readable- robust- correct- manageable- documentedNot necessarily in this order of importance
Wednesday, September 4, 13
Objectives
Writing and commenting a program that solves a linear equation
Introduction
•Writing a bare-bone program that exploits some features of OO
•Introducing tools for I/O
•Talking of other various aspects of programming at convenience
R. RigonWednesday, September 4, 13
Problem analysis
The problem is quite trivial. We look for the solution of a single linear
equation:
One solution is known to exist and be equal to:
R. Rigon
Problem analysis
Wednesday, September 4, 13
package org.geoframe.first;
public class linearequation { static double a=1; static double b=-2;
! public static void main(String[] args) {! ! System.out.println( - b/a);! }
}
Here the simplest programactually this solves a particular case:
Various things to note: for the first time we have defined variable these two
variables are said to be static double
R. Rigon
Coding right away
Wednesday, September 4, 13
static (when applied to a variable):
• It is a variable which belongs to the class and not to object
(instance)
• Static variables are initialized only once , at the start of the
execution . These variables will be initialized first, before the
initialization of any instance variables
• A single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and
doesn’t need any object
• Syntax : <class-name>.<variable-name>
R. Rigon
Java
Wednesday, September 4, 13
double:
is the representation of real numbers in a computer,
• the double data type is a double-precision 64-bit IEEE 754 floating point. Its
range of values is beyond the scope of this discussion, but is specified in the
Floating-Point Types, Formats, and Values section of the Java Language
Specification. For decimal values, this data type is generally the default
choice. As mentioned above, this data type should never be used for precise
values, such as currency.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
R. Rigon
Java
Wednesday, September 4, 13
•byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
•short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
•int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.
besides double Java implements:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
R. Rigon
Java
Wednesday, September 4, 13
• long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
• float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimaland other useful classes provided by the Java platform.
besides double Java implements:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
R. Rigon
Java
Wednesday, September 4, 13
• boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
• char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
besides double Java implements:
They are called “primitive data types” and are not object. However wrapper class
are provided (Double, Float, Boolean, etc) that have all the properties of the classes.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
R. Rigon
Java
Wednesday, September 4, 13
Some further things to note:
•the variables used (that can be either primitive types or objects) must
be declared
•the variable are also initialized to a value
•declaration and initialization are inside the class, but outside the method
(in principle they can be accessed by any other method that we can add to
the class)
R. Rigon
Java
Wednesday, September 4, 13
Clearly we are not satisfied with this program
To satisfy our analysis, we have to:
•consider any couple of a and b
•avoid the case in which a=0
besides to solve the equation
We have three actions here, and we can think to split these actions in
various classes, and various files
R. Rigon
Java
Wednesday, September 4, 13
1 - One class to input the data and control them
2 - One class to execute the task
http://docs.oracle.com/javase/tutorial/java/concepts/class.html
Classes are often said to represent physical objects.
In fact they also represent actions and algorithms, i.e. abstract concepts.
R. Rigon
Java
Wednesday, September 4, 13
package org.geoframe.first;
public class LinearEquationSolver { private double a,b,sol=Double.NaN; public LinearEquationSolver(double a, double b){
....the code here solves the equation ... } public double getSolution(){
....the code here accesses the solution... } public static void main(String[] args){ ....this is useful to try the solver ... }}
Let’s concentrate on the task of
solving the mathematical problem
Variable declaration
methods
R. Rigon
Coding
Wednesday, September 4, 13
Variable declaration:
The only particular thing is the assignment to Double.NaN which is
“not a number”. This will allow, eventually some tests. Variables are
private and can be accessed only by methods inside the class.
This construct implements an object oriented concept called
information hiding.
Methods:
Of the methods one has the same name as the class, and is a constructor,
main( ) has been already covered in the previous slides’ series.
The other method is used to access the solution and make it available
by other classes.
R. Rigon
Java
Wednesday, September 4, 13
In computer science, information hiding is the principle of
segregation of the design decisions in a computer program that are
most likely to change, thus protecting other parts of the program
from extensive modification if the design decision is changed. The
protection involves providing a stableinterface which protects the
remainder of the program from the implementation (the details that
are most likely to change).
Written another way, information hiding is the ability to prevent
certain aspects of a class or software component from being
accessible to its clients, using either programming language features
(like private variables) or an explicit exporting policy.
http://en.wikipedia.org/wiki/Information_hiding
R. Rigon
OO
Wednesday, September 4, 13
A Java Constructor:
A java constructor has the same name as the name of the class
to which it belongs. Constructor’s syntax does not include a
return type, since constructors never return a value.
Constructors may include parameters of various types. When the
constructor is invoked using the new operator, the types must
match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments
and performs no special actions or initializations, when no
explicit constructors are provided.
If a constructor is explicitly provided, this overwrite the default
one and needs to be used.
However, a class can have multiple constructors
R. Rigon
Java
Wednesday, September 4, 13
A look to the main( ):
public static void main(String[] args){ double a =3,b=4,sol; System.out.println("\nThis is the LinearEquationSolver
main( )\n"); LinearEquationSolver ll = new LinearEquationSolver(a,b); sol=ll.getSolution(); System.out.println("The solution of "+a+" x + "+b+" \\
== 0 is: x = "+sol); System.out.println("\nEnd of Computation\n"); }
These variables lives here. They cannot be confused with the variables with the
same names inside the class definition
R. Rigon
Code inspection
Wednesday, September 4, 13
public static void main(String[] args){ double a =3,b=4,sol; System.out.println("\nThis is the LinearEquationSolver
main( )\n"); LinearEquationSolver ll = new LinearEquationSolver(a,b); sol=ll.getSolution(); System.out.println("The solution of "+a+" x + "+b+" \\
== 0 is: x = "+sol); System.out.println("\nEnd of Computation\n"); }
A look to the main( ):
This is not strictly necessary. However, as you realized, since any class can have its
main( ), this is useful to know which class you are actually executing.
R. Rigon
Code inspection
Wednesday, September 4, 13
public static void main(String[] args){ double a =3,b=4,sol; System.out.println("\nThis is the LinearEquationSolver
main( )\n"); LinearEquationSolver ll = new LinearEquationSolver(a,b); sol=ll.getSolution(); System.out.println("The solution of "+a+" x + "+b+" \\
== 0 is: x = "+sol); System.out.println("\nEnd of Computation\n"); }
A look to the main( ):
This is not strictly necessary either. However, in more complex programs, which
output to files, is better to have something that tells you that the program finished.
R. Rigon
Code inspection
Wednesday, September 4, 13
public static void main(String[] args){ double a =3,b=4,sol; System.out.println("\nThis is the LinearEquationSolver
main( )\n"); LinearEquationSolver ll = new LinearEquationSolver(a,b); sol=ll.getSolution(); System.out.println("The solution of "+a+" x + "+b+" \\
== 0 is: x = "+sol); System.out.println("\nEnd of Computation\n"); }
A look to the main( ):
This command makes a lot of things:
R. Rigon
Code inspection
Wednesday, September 4, 13
LinearEquationSolver ll = new LinearEquationSolver(a,b);
The left side is a declaration of a type LinearEquationSolver: each class is a type
and each variable must be declared !
LinearEquationSolver ll = new LinearEquationSolver(a,b);
The right side makes two thing:
•allocate in the memory (in the heap) of the computer the space for an object of
type LinearEquationSolver
•Trough the arguments a and b provides also the parameters to build a
particular type of LinearEquationSolver (and actually solves it)
R. Rigon
Code use
Wednesday, September 4, 13
The stack and the heap
Difference between stack and heap memory is common programming
question asked by beginners learning Java or any other programming
language. Stack and heap memory are two terms programmers starts
hearing once they started programming but without any clear and
definite explanation. Lack of knowledge on what is heap in Java and
what is stack memory in Java, results in misconcepts related to stack
and heap. To add to this confusion, stack is also a data structure which
is used to store elements in LIFO(Last In First out) order and available in
Java API as java.util.Stack.
R. Rigon
Java
Wednesday, September 4, 13
The stack and the heap
The JVM divided the memory into following sections.
1. Heap2. Stack3. Code4. Static
This division of memory is required for its effective management.
R. Rigon
Java
Wednesday, September 4, 13
1. The code section contains your bytecode.
2. The Stack section of memory contains methods, local variables and
reference variables.
3. The Heap section contains Objects (may also contain reference
variables).
4. The Static section contains Static data/methods.
Of all of the above 4 sections, you need to understand the allocation of
memory in Stack & Heap the most, since it will affect your programming
efforts
To know more:http://stackoverflow.com/questions/3646632/does-the-java-primitives-go-on-the-stack-or-the-heap
R. Rigon
Java
Wednesday, September 4, 13
public static void main(String[] args){ double a =3,b=4,sol; System.out.println("\nThis is the LinearEquationSolver
main( )\n"); LinearEquationSolver ll = new LinearEquationSolver(a,b); sol=ll.getSolution(); System.out.println("The solution of "+a+" x + "+b+" \\
== 0 is: x = "+sol); System.out.println("\nEnd of Computation\n"); }
A look to the main( ):
This command makes access the solution (otherwise private of the class).
Sometimes this kind of method is called “a getter”.
R. Rigon
Code inspection
Wednesday, September 4, 13
public static void main(String[] args){ double a =3,b=4,sol; System.out.println("\nThis is the LinearEquationSolver
main( )\n"); LinearEquationSolver ll = new LinearEquationSolver(a,b); sol=ll.getSolution(); System.out.println("The solution of "+a+" x + "+b+" \\
== 0 is: x = "+sol); System.out.println("\nEnd of Computation\n"); }
A look to the main( ):
This command (a call to a method of a class) print to the video (to the system
console actually) the result.
R. Rigon
Code inspection
Wednesday, September 4, 13
A look to LinearEquationSolver method:
public LinearEquationSolver(double a, double b){ if(a !=0){ sol = -b/a; } else{ throw new RuntimeException("\nA solution does not exists\n"); } }
By default a constructor is package visible, this makes it visible even outside the
package
R. Rigon
Code inspection
Wednesday, September 4, 13
public LinearEquationSolver(double a, double b){ if(a !=0){ sol = -b/a; } else{ throw new RuntimeException("\nA solution does not exists\n"); } }
A look to LinearEquationSolver method:
This is a classic if( ){ }else { } statement. If the argument is true the
statements among the first braces is executed, otherwise the second
R. Rigon
Code inspection
Wednesday, September 4, 13
public LinearEquationSolver(double a, double b){ if(a !=0){ sol = -b/a; } else{ throw new RuntimeException("\nA solution does not exists\n"); } }
A look to LinearEquationSolver method:
This is the solution. Please notice that he solution is assigned to the variable sol, a
static one, which is visible to the whole class (and does not need to be defined
here)
R. Rigon
Code inspection
Wednesday, September 4, 13
public LinearEquationSolver(double a, double b){ if(a !=0){ sol = -b/a; } else{ throw new RuntimeException("\nA solution does not exists\n"); } }
A look to LinearEquationSolver method:
If a is not 0 (that’s the meaning of the argument of a !=0, then an error message is
issued. Java has a built-in strategy to treat errors, and in its jargon it is said that an
error is thrown.
R. Rigon
Code inspection
Wednesday, September 4, 13
Throw an error
Well, one can realize that if both a=0 and b=0, the equation is an identity.
So the try ... catch statement should be changed as follows:
if(a !=0){ sol = -b/a; } else if(b !=0) { throw new RuntimeException("\nA solution does not exists because a =0\n"); }else { throw new RuntimeException("\nThis is the trivial identity 0=0\n"); }
R. Rigon
Java
Wednesday, September 4, 13
A look to LinearEquationSolver method:
R. RigonWednesday, September 4, 13
public double getSolution(){ if(Double.isNaN(sol)) { throw new RuntimeException("\nlinearequationSolver not initialized\n"); }else{ return sol; } }
A look to getSolution( ) method:
A longer story here: Double is actually a class-wrapper of the primitive type
double and the argument test if sol is a NaN (this construct is necessary, the ==
equality cannot be used here). Actually this fact could never happen here, because
the constructor (which is mandatory) initialize it.
R. Rigon
Code inspection
Wednesday, September 4, 13
public double getSolution(){ if(Double.isNaN(sol)) { throw new RuntimeException("\nlinearequationSolver not initialized\n"); }else{ return sol; } }
A look to getSolution( ) method:
This is the exception thrown if sol would be a NaN. (I initialized it to a NaN in the
main body of the class).
Code inspection
Wednesday, September 4, 13
public double getSolution(){ if(Double.isNaN(sol)) { throw new RuntimeException("\nlinearequationSolver not initialized\n"); }else{ return sol; } }
A look to getSolution( ) method:
The return keyword allow to return the solution sol which is passed over to a
double variable which must be catched when the getSolution( ) is used (see
the main( ) )
R. Rigon
Code inspection
Wednesday, September 4, 13
public static void main(String[] args){ double a =3,b=4,sol;
....... Omitted code ....
System.out.println("\nNow testing the try ... catch "); a=0; try{ LinearEquationSolver ll1 = new LinearEquationSolver(a,b); sol=ll1.getSolution(); System.out.println("The solution of "+a+" x + "+b+" == 0 is: x = "+sol); } catch(RuntimeException e){ TextIO.put(e); }
System.out.println("\nEnd of Computation\n"); }
A better main( )
This code has been added to test the try-catch statement
R. Rigon
Code inspection
Wednesday, September 4, 13
public static void main(String[] args){ double a =3,b=4,sol;
....... Omitted code ....
System.out.println("\nNow testing the try ... catch "); a=0; try{ LinearEquationSolver ll1 = new LinearEquationSolver(a,b); sol=ll1.getSolution(); System.out.println("The solution of "+a+" x + "+b+" == 0 is: x = "+sol); } catch(RuntimeException e){ TextIO.put(e); }
System.out.println("\nEnd of Computation\n"); }
A better main( )
Not very much of a treatment indeed. Just telling that the solution does not exists
if a =0
R. Rigon
Code inspection
Wednesday, September 4, 13
How could we have implemented the
getSolution( ) better
R. Rigon
Questions ?
Wednesday, September 4, 13
Summary
We have solved a linear equation. The steps trough which we passed
were:
•The analysis of the mathematical problem
•The decision of splitting the problem into 2 classes
In implementing the second class, we adopted a pattern, which is a
particular way for doing it, that experienced OO-programmer think to
be solid and robust. In particular we used a constructor method for
solving the equation, and a getter method for getting the solution,
otherwise hidden to rest of the world.
R. Rigon
To sum up
Wednesday, September 4, 13
UML 2.0 representation of the class
LinearEquationSolver
- a: double- b: double
+LinearEquationSolver ( )+getSolution ( )
- sol: double
The class we used for the algorithm is represented in the above figure. On
top goes the name of the class. In the center of the body there are the
variables used. On the bottom part the methods of the class. This way of
representing the graphically the class is called class diagram in UML 2.0
(http://www.youtube.com/watch?v=3cmzqZzwNDM)
This is the name of the class
These are the fields of the class
These are the methods of the class
UML
Wednesday, September 4, 13
UML 2.0 representation of the class
LinearEquationSolver
+LinearEquationSolver (a:double, b:double)+getSolution ( ): double
The class we used for the algorithm is represented in the above figure. On
top goes the name of the class. In the center of the body there are the
variables used. On the bottom part the methods of the class. This way of
representing the graphically the class is called class diagram in UML 2.0
(http://www.youtube.com/watch?v=3cmzqZzwNDM)
•The minuses say that the field are private;
•a “+” would indicate a public class;
•a “#” a protected class
- a: double- b: double- sol: double
R. Rigon
UML
Wednesday, September 4, 13
Getting the parameters from the standard input
It seems a secondary task ... but one would not to hard-coding the
parameters inside the class.
We want the program asking for it and we want to insert them at run
time.
We can think to defer to a class the
IO. Thus, we can simply implement
the class, test it and use inside the
general program.
GetTwoDoubleParameters
-a: double-b: double
+setParameter(): void
R. Rigon
UML
Wednesday, September 4, 13
Thank you for your attention.
G.U
lric
i, 2
00
0 ?
It ends here
Wednesday, September 4, 13