SlideShare a Scribd company logo
1A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Frank NIELSEN
nielsen@lix.polytechnique.fr
A Concise and
Practical
Introduction to
Programming
Algorithms in Java
Chapter 5: Classes and objects
2A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
So far...: Executive summary
● Lecture 1: Variable, Expression, Assignment
● Lecture 2: Loops (for while do)
Conditional structures (if else switch)
Boolean predicate and connectors (|| &&)
Loop escape break
● Lecture 3: functions (static) and recursion (terminal or not)
● Lecture 4: Objects
3A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Indenting source code (.java)
● Increase code readibility
● Avoid mistyping bugs (matching { })
Source code formatter, pretty printer, beautifier
Different conventions are possible (but choose one)
Implemented more or less in Software (S/W) Nedit, Jcreator, Jindent, etc...
4A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
http://java.sun.com/docs/codeconv/
Identing source code (.java)
Examples for if else conditions
5A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Indenting source code (.java)
http://java.sun.com/docs/codeconv/
6A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Indenting source code (.java)
● Bytecode size and indentation:
Does not change fundamentally
● Bytecode is not human readable
Demo Indent.java:
notepad
Jcreator
& produced bytecode Indent.class
open bytecode
7A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Identing source code (.java)
Sometimes in Java code (Internet), comments include commands
for generating automatically documentation by other tools:
... Like javadoc (paradigm literate programming, etc.)
http://java.sun.com/j2se/javadoc/
La classe TC se trouve a:
http://www.enseignement.polytechnique.fr/informatique/profs/Julien.Cervelle/TC/
Class TC
8A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions in Java
● Static functions that returns a type (eventually void)
● Functions are called inside the main procedure
(or in other function body)
● Displaying and calling function are different
(be not confused with SciLab or Maple
System.out.println(function());
● Java is a compiled OO language , not an interpreter
9A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions: void/display
Java cannot cast void type into a String,
so the compiler javac generates an error.
(type checking)
class Functions
{
static void PascalTriangle(int depth)
{//...
return ;
}
public static void main(String[] toto)
{
System.out.println(PascalTriangle(5));
}
}
'void' type not allowed here'void' type not allowed here
10A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions: void/display
Java is not an interpreter like SciLab or Maple
Functions are called within a block of instructions...
... not in the console!!!!class Functions
{
static double f(double x)
{return x;}
static void main(String[] args)
{ }
}
11A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Variables: static or not...
Static variables are declared in the class bodyclass body
class Toto
{
static int count1, count2;
...
}
Otherwise non-static variables (usual) are
declared in function bodiesfunction bodies (main, etc.)
public static void main(String[] args)
{double x;int i;}
● Variables are kept in memory in their function scope {...}
● Static variables are kept in memory and can be shared by
several functions...
12A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
class Functions
{
static int count1, count2;
static void f1(){count1++;}
static void f2(){count2++;}
public static void main(String[] args)
{
count1=0;
count2=0;
for(int i=0;i<1000;i++)
{
double rand=Math.random();
if (rand<0.5)
{f1();}
else
{f2();}
}
System.out.println("count1:"+count1);
System.out.println("count2:"+count2);
}
}
static or not...
13A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Java is pass by value
...and arrays and objects are pass by reference
class BadSwap
{
static void swap(int arg1, int arg2)
{
int tmp;
tmp=arg1;
arg1=arg2;
arg2=tmp;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
System.out.println("a:"+a+" b:"+b);
swap(a,b);
System.out.println("After the swap...");
System.out.println("a:"+a+" b:"+b);
}
}
14A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Managing memory & functions
When calling a function f, the current function (main) indicates
.....where to write the value of the result
To obtain the result, function f uses a local memory
In that local memory, values of arguments are available
//current function body {}
int a=3,b=2;
swap(a,b)
Memory address
main
Value of a
Value of b
s
w
a
p
Value of arg1
Value of arg2
Value of tmp
15A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
static void swap(int arg1, int arg2)
{
int tmp;
tmp=arg1;
arg1=arg2;
arg2=tmp;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
swap(a,b);
}
Memory address
main
3
2
1. Create memory for local variables of function main
2. Assign values for a and b
b
a
16A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
static void swap(int arg1, int arg2)
{
int tmp;
tmp=arg1;
arg1=arg2;
arg2=tmp;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
swap(a,b);
}
3. create local space for function swap
Memory address
main
3
2
s
w
a
p
arg1
arg2
tmp
b
a
17A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
static void swap(int arg1, int arg2)
{
int tmp; // 0 is default value
tmp=arg1;
arg1=arg2;
arg2=tmp;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
swap(a,b);
}
4. evaluate expression for getting values of arg1 and arg2
swap(a,b) becomes swap(3,2)
Memory address
main
3
2
s
w
a
p
arg1
arg2
tmp
b
a
3
2
0
18A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
static void swap(int arg1, int arg2)
{
int tmp; // 0 is default value
tmp=arg1;
arg1=arg2;
arg2=tmp;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
swap(a,b);
}
5. Execute instruction tmp=arg1
Memory address
main
3
2
s
w
a
p
arg1
arg2
tmp
b
a
3
2
3
19A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
static void swap(int arg1, int arg2)
{
int tmp; // 0 is default value
tmp=arg1;
arg1=arg2;
arg2=tmp;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
swap(a,b);
}
Memory address
main
3
2
s
w
a
p
arg1
arg2
tmp
b
a
2
2
3
6. Execute instruction arg1=arg2
20A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
static void swap(int arg1, int arg2)
{
int tmp; // 0 is default value
tmp=arg1;
arg1=arg2;
arg2=tmp;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
swap(a,b);
}
Memory address
main
3
2
s
w
a
p
arg1
arg2
tmp
b
a
2
3
3
7. Execute the sequence of instructions in the swap block
Notice that here the swapped has been performed
21A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
static void swap(int arg1, int arg2)
{
int tmp; // 0 is default value
tmp=arg1;
arg1=arg2;
arg2=tmp;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
swap(a,b);
}
Memory address
main
3
2
s
w
a
p
arg1
arg2
tmp
b
a
2
3
3
5. Execute the sequence of instructions in the swap block
22A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
static void swap(int arg1, int arg2)
{
int tmp; // 0 is default value
tmp=arg1;
arg1=arg2;
arg2=tmp; // we omitted return ;
}
public static void main(String[] toto)
{
int a=3;
int b=2;
swap(a,b);
}
Memory address
main
3
2 b
a
8. Return result of function swap (here void!!!)
9. Release memory allocated for swap
Variables a and b
have kept their original values
23A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Memory for static variables
class SwapStatic
{
static int a,b;
static void swap()
{
...
}
public static void main(String[] toto)
{
a=3;
b=2;
swap();
}
}
Memory address
main
3
2 b
a
Memory for static variables
of class SwapStatic
swaptmp0
24A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
class SwapStatic
{
static int a,b;
static void swap()
{
int tmp;// ok not to be static
tmp=a;
a=b;
b=tmp;
}
public static void main(String[] toto)
{
a=3;
b=2;
System.out.println("a:"+a+" b:"+b);
swap();
System.out.println("After the swap...");
System.out.println("a:"+a+" b:"+b);
}
}
By passing
using static
25A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Memory for arrays and
pass by reference
Arrays are allocated a continuous memory location
for storing TYPE elements
The value of the array variable is a reference to the beginning of the array
Memory for arrays (heap)
TypeElement [ ] tab= new TypeElement[size]
tab[0]
tab[1]
tab[size-1]
Array variable tab is a reference
26A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Memory management using new
Type [] tab=new Type[Expression];
● Evaluate Expression to get an integer value.
● Arrays are stored not in the local function memory,
but rather in the global program memory:
heap, tas en francais
● A cell (array element) in the heap (program memory)
is accessible by any function which has
as a local (non-static) variable a reference to the array.
27A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
class ArrayReference
{
public static void swap(int [] t, int i, int j)
{
int tmp;
tmp=t[i];
t[i]=t[j];
t[j]=tmp;
}
public static void Display(int [] tab){... »
public static void main(String[] args)
{
//int [] array=new int[10];
int [] array={0,1,2,3,4,5,6,7,8,9};
Display(array);
swap(array,1,2);
Display(array);
}
}
0 1 2 3 4 5 6 7 8 9
0 2 1 3 4 5 6 7 8 9
28A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Memory management using new
4 4 4 4 4 4 4 4 4 4
4 4 0 4 4 4 4 4 4 4
class BuildArray{
// Return a reference to an array
public static int [] BuildArray(int size, int defaultval)
{
int [] result=new int[size];
for(int i=0;i<size;i++) result[i]=defaultval;
return result;
}
public static void Zero(int[] tab, int pos)
{
tab[pos]=0;
}
public static void main(String [] argarray)
{
int v []=BuildArray(10,4);
Display(v);
Zero(v,2);
Display(v);
}
29A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Synopsis of this lecture
● Objects and records (fields, enregistrements)
● Object constructors
● Class type variables: References
● Functions on objects: Methods
● Array of objects
● Examples
30A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Why do we need objects?
Java is an oriented-object (OO) programming language
Encapsulate functions/data acting on a same domain
For example, the String type
Allows one to work on complex entities: Data structures
For examples:
● Dates are triplets of numbers (MM/DD/YYYY)
● 2D point with co-ordinates (x,y)
● Student: Lastname, Firstname, Group, etc.
These are called object records (fields)
31A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Declaring classes and objects
● Choose record/field names (enregistrement)
● Define a type of each record
● Similar to variables but without keyword static
● Class is then a new type with name...
... the class name
32A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Toy example public class Date
{
int dd;
int mm;
int yyyy;
}
Fields (champs/enregistrements) are also called object variables
Do not have the leading keyword static
Let day be a variable of type Date then
day.dd day.mm dd.yyyy
are variables of type int
33A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Toy example
public class Student
{
String Lastname;
String Firstname;
int Company;
double [ ] Marks;
...
}
Class Student encapsulates data attached to a student identity.
34A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Constructors
To use an object, we first need to build it
We construct an object using the instruction new
But first, we need to define a constructor for the class
A constructor is a method (non-static function) ...
...bearing the class' name
This method does not return a result but assigns...
...values to the object's field
Use this.field to access field of the object
35A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
public class Date
{
int dd;
int mm;
int yyyy;
// Constructor
public Date(int day, int month, int year)
{this.dd=day;
this.mm=month;
this.yyyy=year;}
}
Constructors
Date day=new Date(23,12,1971);
Create an object of type Date
36A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
public class Date
{
int dd;
int mm;
int yyyy;
public Date(int day, int month, int year)
{
this.dd=day;
this.mm=month;
this.yyyy=year;
}
}
Public class YYY stored in YYY.java
class TestDate{
public static void main(String args)
{
Date day=new Date(23,12,1971);
}
}
Filename: Date.java
Filename: TestDate.java
37A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Constructors
● Possibly several constructors (with different signatures)
● Best, to define a single one with all fields initialized
● Keyword this means the currently built object
(not compulsory to write it explicitly but recommended)
public Date(int day, int month, int year)
{dd=day;
this.mm=month;
yyyy=year;
}
● If no constructor is built, the system uses the by-default one
(not recommended)
Date day=new Date();// see poly pp. 59-61
day.yyyy=1971;
38A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
The null object
● This object is common to all classes
● Not possible to assign its fields
● Nor retrieve values of its fields, either
(exception nullPointerException raised)
● Used for initializing a variable of type object:
Student stud=null;
● It is often recommender to check if an object is null or not:
if( stud!=null) stud.company=2;
39A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions/methods on objects
Objects can be parameters of functions
static TypeF F(Object1 obj1, ..., ObjectN objN)
Functions may return an object as a result:
static boolean isBefore (Date d1, Date d2)
static Date readDate()
40A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Examplepublic class Date
{
int dd;
int mm;
int yyyy;
public static final String[ ] months={
"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December"
};
// Constructor
public Date(int day, int month, int year)
{
this.dd=day;
this.mm=month;
this.yyyy=year;
}
}
41A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Example
class TestDate{
static void Display(Date d){
System.out.println("The "+d.dd+" "+Date.months[d.mm-
1]+" of "+d.yyyy);
}
static boolean isBefore(Date d1, Date d2)
{
boolean result=true;
if (d1.yyyy>d2.yyyy) result=false;
if (d1.yyyy==d2.yyyy && d1.mm>d2.mm) result=false;
if (d1.yyyy==d2.yyyy && d1.mm==d2.mm && d1.dd>d2.dd)
result=false;
return result;
}
public static void main(String[] args)
{
Date day1=new Date(23,12,1971);
Display(day1);
Date day2=new Date(23,6,1980);
System.out.println(isBefore(day1,day2));
}
}
42A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
class TestDate{
...
static Date lireDate()
{
int jj, mm, aaaa;
System.out.println("Jour?");
jj=TC.lireInt();
System.out.println("Mois?");
mm=TC.lireInt();
System.out.println("Annee?");
aaaa=TC.lireInt();
Date day=new Date(jj,mm,aaaa);
return day;
}
public static void main(String[] args)
{
Display(lireDate());
}
}
43A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Variable of Type Object: Reference
A variable of type Object is a reference on that object
It stores the memory address of this referenced object
Thus when we write:
Date day1=new Date(23,12,1971);
Date day2=day1;
Display(day2);
day2.mm=6;
Display(day1);
The date d1 is not copied, only the reference of...
...d1 is assigned to d2
44A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Copying objects...
To copy (clone) an object to another we need to do it fieldwise
// Two Scenarii:
// day2 has already been created...
day2.dd=day1.dd;
day2.mm=day1.mm;
day2.yyyy=day1.yyyy;
// day2 object has not yet been created...
static Date Copy(date day1)
{
Date newdate=new Date (day1.dd,day1.mm,day1.yyyy);
return newdate;
}
...
Date d2=Copy(d1);
45A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Comparing two objects...
Do not use == for object equality
To compare objects, use a tailored predicate:
static boolean isEqual(Date d1, Date d2)
{
return (d1.dd == d2.dd &&
d1.mm == d2.mm &
d1.yyyy== d2.yyyy);
}
46A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Comparing two objects...
public static void main(String[] args)
{
Date day1=new Date(23,12,1971);
Date day2=day1; // beware not copying here.
Just memory reference
Date day3=new Date(23,12,1971);
System.out.println(isEqual(day1,day3));
System.out.println(day1);
System.out.println(day2);
System.out.println(day3);
}
Physical (memory) versus logical equality
47A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Array of objects
● Since classes defines new types...
... we can create array of objects
● To build an array of objects: new nameT[sizearray]
Date [ ] tabDates=new Date[31];
● When an array of object is built, the elements Date[i]
are all initialized to the null object.
48A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Example
public class Date
{
...
void Display()
{
System.out.println(dd+" "+months[mm-1]+" "+yyyy);
}
...
}
public class XEvent
{
Date when;
String what;
public XEvent(Date d, String text)
{
this.when=d;
this.what=text;
}
} Filename XEvent.java
Filename Date.java
49A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
public class TestXEvent
{
public static void Display(XEvent e)
{
System.out.print(e.what+": ");
e.when.Display();
}
public static void main(String [] args)
{
Date d1=new Date(26,6,2008);
XEvent e1=new XEvent(d1,"Birthday Julien");
Display(e1);
XEvent [] tabEvent=new XEvent[5];
tabEvent[0]=e1;
}
}
50A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
public class TestXEvent
{public static void Display(XEvent e)
{ System.out.print(e.what+": ");
e.when.Display(); }
public static boolean older(XEvent e1, XEvent e2)
{return Date.isBefore(e1.when,e2.when);}
public static XEvent oldest(XEvent[] tab)
{
XEvent result=tab[0];
for(int i=1;i<tab.length;++i)
if (older(tab[i],result)) result=tab[i];
return result;
}
public static void main(String [] args)
{
Date d1=new Date(26,6,2003);
XEvent e1=new XEvent(d1,"Birthday Julien");
Date d2=new Date(20,11,2000);
XEvent e2=new XEvent(d2,"Birthday Audrey");
Date d3=new Date(23,6,1971);
XEvent e3=new XEvent(d3,"Birthday Me");
Display(e1);
XEvent [] tabEvent=new XEvent[3];
tabEvent[0]=e1;tabEvent[1]=e2;tabEvent[2]=e3;
System.out.print("Oldest person::");Display(oldest(tabEvent));
}
}
51A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Objects with array members
Fields of objects may be arrays themselves
always built with new Type[sizearray]
// sizearray might be an expression, i.e., 3*n+2
It is not necessary at compile time to know statically...
.... the array sizes
class Polynome{
int degree;
double [ ] coefficients;
};
52A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Strings: Basic objects in Java
● A string of character is an object with type String
● A variable of type String is a reference on that object:
String school= ''Ecole Polytechnique'';
String vars=school;
● Once built, a string object cannot be modified
● Beware: use only for moderate length strings,
otherwise use the class StringBuffer
53A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Class String: Some methods
A method is a function or procedure on an object class
Method Length() : gives the number of characters
String s= ''anticonstitutionnellement'';
System.out.println(s.length());
Method equals():
s1.equals(s2): Predicate that returns true if and only if the
two strings s1 and s2 are made of the same sequence of characters.
String s1=''Poincare'';
String s2=TC.lireMotSuivant();
System.out.println(s1.equals(s2));
Beware: s1==s2 is different!
It compares the reference of the strings.
(Physical versus logical equality test)
54A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Class String in action...
55A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Class String: More methods
Method charAt():
s.charAt(i) gives the character at the (i+1)th position in string s.
String s= ''3.14159265'';
System.out.println(s.charAt(1));
56A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Method compareTo():
u.compareTo(v) compares lexicographically the strings u with v.
String u=''lien'', v=''lit'', w=''litterie'';
System.out.println(u.compareTo(v));
System.out.println(v.compareTo(w));
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
From Javadoc...
57A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Lexicographic total order on strings
● If there is a position k at which strings differ:
this.charAt(k)-anotherString.charAt(k):
String s1="Marin",s2="Martin"; // -11 from i to t
int index=3;// meaning 4th pos
System.out.println(s1.compareTo(s2));
System.out.println(s1.charAt(index)-s2.charAt(index));
● else the difference of string lengths:
this.length()-anotherString.length():
String s3="Bien",s4="Bienvenue";
System.out.println(s3.compareTo(s4));
System.out.println(s3.length()-s4.length());
58A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Class String: More methods
59A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Demystifying the main function
class ClassName
{
public static void main(String[ ] args)
{
...
}
}
Function main has an array of string of characters as arguments
These strings are stored in args[0], args[1], ...
... when calling java main s0 s1 s2 s3
Use Integer.parseInt() to convert a string into an integer
60A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Parsing arguments in the main function
61A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Parsing arguments in the main function
62A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
More evolved Java
program skeleton...
2 versus (!=) 3
(2,1)
(3,4)
class Point
{
int x,y;
Point(int xx, int yy){x=xx;y=yy;}
public void Display()
{System.out.println("("+x+","+y+")")}
} // end of class Point
class Skeleton
{
// Static class variables
static int nbpoint=0;
static double x;
static boolean [] prime;
static int f1(int p){return p/2;}
static int f2(int p){return 2*p;}
public static void main(String [] argArray)
{
System.out.println(f2(f1(3))+" versus (!=) "+f1(f2(3)));
Point p,q;
p=new Point(2,1); nbpoint++;
q=new Point(3,4); nbpoint++;
p.Display();q.Display();
} }
63A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen

More Related Content

What's hot (20)

C Prog - Functions
C Prog - FunctionsC Prog - Functions
C Prog - Functions
vinay arora
 
C++11
C++11C++11
C++11
Quang Trần Duy
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
Stephane Gleizes
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)
MoonSheikh1
 
The Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 MigrationThe Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 Migration
Joel Falcou
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#
tcaesvk
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
System verilog assertions
System verilog assertionsSystem verilog assertions
System verilog assertions
HARINATH REDDY
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Modern C++
Modern C++Modern C++
Modern C++
Richard Thomson
 
Software Abstractions for Parallel Hardware
Software Abstractions for Parallel HardwareSoftware Abstractions for Parallel Hardware
Software Abstractions for Parallel Hardware
Joel Falcou
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
AravindSankaran
 
Learn C# Programming Polymorphism & Operator Overloading
Learn C# Programming Polymorphism & Operator OverloadingLearn C# Programming Polymorphism & Operator Overloading
Learn C# Programming Polymorphism & Operator Overloading
Eng Teong Cheah
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
Francesco Casalegno
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
Delays in verilog
Delays in verilogDelays in verilog
Delays in verilog
JITU MISTRY
 
C Prog - Functions
C Prog - FunctionsC Prog - Functions
C Prog - Functions
vinay arora
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
Stephane Gleizes
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)
MoonSheikh1
 
The Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 MigrationThe Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 Migration
Joel Falcou
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#
tcaesvk
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
System verilog assertions
System verilog assertionsSystem verilog assertions
System verilog assertions
HARINATH REDDY
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Software Abstractions for Parallel Hardware
Software Abstractions for Parallel HardwareSoftware Abstractions for Parallel Hardware
Software Abstractions for Parallel Hardware
Joel Falcou
 
Learn C# Programming Polymorphism & Operator Overloading
Learn C# Programming Polymorphism & Operator OverloadingLearn C# Programming Polymorphism & Operator Overloading
Learn C# Programming Polymorphism & Operator Overloading
Eng Teong Cheah
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
Delays in verilog
Delays in verilogDelays in verilog
Delays in verilog
JITU MISTRY
 

Viewers also liked (20)

Commercial radio
Commercial radioCommercial radio
Commercial radio
idil moali
 
Simplifying Gaussian Mixture Models Via Entropic Quantization (EUSIPCO 2009)
Simplifying Gaussian Mixture Models Via Entropic Quantization (EUSIPCO 2009)Simplifying Gaussian Mixture Models Via Entropic Quantization (EUSIPCO 2009)
Simplifying Gaussian Mixture Models Via Entropic Quantization (EUSIPCO 2009)
Frank Nielsen
 
2013年8月10日 academic coaching oriented education
2013年8月10日 academic coaching oriented education2013年8月10日 academic coaching oriented education
2013年8月10日 academic coaching oriented education
SUGAWARA, Hideyuki
 
Gurumurthy Kalyanaram on Advertising Response Function in Marketing Science
Gurumurthy Kalyanaram on Advertising Response Function in Marketing ScienceGurumurthy Kalyanaram on Advertising Response Function in Marketing Science
Gurumurthy Kalyanaram on Advertising Response Function in Marketing Science
Gurumurthy Kalyanaram
 
Dig marketing pres
Dig marketing presDig marketing pres
Dig marketing pres
Alex Ham
 
Designing rugged camera into E/O systems
Designing rugged camera into E/O systemsDesigning rugged camera into E/O systems
Designing rugged camera into E/O systems
Adimec
 
Gabrielgonzalez tarea
Gabrielgonzalez tareaGabrielgonzalez tarea
Gabrielgonzalez tarea
gabrieling
 
Testimonials for Attorney David Coolidge
Testimonials for Attorney David CoolidgeTestimonials for Attorney David Coolidge
Testimonials for Attorney David Coolidge
David Coolidge
 
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Student-Produced Event Broadcasting
Student-Produced Event BroadcastingStudent-Produced Event Broadcasting
Student-Produced Event Broadcasting
Jena Graham
 
Gabrielgonzalez tarea
Gabrielgonzalez tareaGabrielgonzalez tarea
Gabrielgonzalez tarea
gabrieling
 
(ISIA 3) Cours d'algorithmique (1995)
(ISIA 3) Cours d'algorithmique (1995)(ISIA 3) Cours d'algorithmique (1995)
(ISIA 3) Cours d'algorithmique (1995)
Frank Nielsen
 
Unit 1 lesson 1
Unit 1 lesson 1Unit 1 lesson 1
Unit 1 lesson 1
tamma07
 
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Drumstick Bars Recipe
Drumstick Bars RecipeDrumstick Bars Recipe
Drumstick Bars Recipe
Kristy Kay
 
Minor Crimes Hurt Ambition by David Coolidge
Minor Crimes Hurt Ambition by David CoolidgeMinor Crimes Hurt Ambition by David Coolidge
Minor Crimes Hurt Ambition by David Coolidge
David Coolidge
 
Strategies for Education & Communicating with Parents
Strategies for Education & Communicating with Parents Strategies for Education & Communicating with Parents
Strategies for Education & Communicating with Parents
Jena Graham
 
091
091091
091
tamma07
 
@ut-of-the-Box™ 10 Steps Process
@ut-of-the-Box™ 10 Steps Process@ut-of-the-Box™ 10 Steps Process
@ut-of-the-Box™ 10 Steps Process
mcollaboration
 
2013年3月18日 日本国際保健医療学会 学生部会
2013年3月18日 日本国際保健医療学会 学生部会2013年3月18日 日本国際保健医療学会 学生部会
2013年3月18日 日本国際保健医療学会 学生部会
SUGAWARA, Hideyuki
 
Commercial radio
Commercial radioCommercial radio
Commercial radio
idil moali
 
Simplifying Gaussian Mixture Models Via Entropic Quantization (EUSIPCO 2009)
Simplifying Gaussian Mixture Models Via Entropic Quantization (EUSIPCO 2009)Simplifying Gaussian Mixture Models Via Entropic Quantization (EUSIPCO 2009)
Simplifying Gaussian Mixture Models Via Entropic Quantization (EUSIPCO 2009)
Frank Nielsen
 
2013年8月10日 academic coaching oriented education
2013年8月10日 academic coaching oriented education2013年8月10日 academic coaching oriented education
2013年8月10日 academic coaching oriented education
SUGAWARA, Hideyuki
 
Gurumurthy Kalyanaram on Advertising Response Function in Marketing Science
Gurumurthy Kalyanaram on Advertising Response Function in Marketing ScienceGurumurthy Kalyanaram on Advertising Response Function in Marketing Science
Gurumurthy Kalyanaram on Advertising Response Function in Marketing Science
Gurumurthy Kalyanaram
 
Dig marketing pres
Dig marketing presDig marketing pres
Dig marketing pres
Alex Ham
 
Designing rugged camera into E/O systems
Designing rugged camera into E/O systemsDesigning rugged camera into E/O systems
Designing rugged camera into E/O systems
Adimec
 
Gabrielgonzalez tarea
Gabrielgonzalez tareaGabrielgonzalez tarea
Gabrielgonzalez tarea
gabrieling
 
Testimonials for Attorney David Coolidge
Testimonials for Attorney David CoolidgeTestimonials for Attorney David Coolidge
Testimonials for Attorney David Coolidge
David Coolidge
 
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Student-Produced Event Broadcasting
Student-Produced Event BroadcastingStudent-Produced Event Broadcasting
Student-Produced Event Broadcasting
Jena Graham
 
Gabrielgonzalez tarea
Gabrielgonzalez tareaGabrielgonzalez tarea
Gabrielgonzalez tarea
gabrieling
 
(ISIA 3) Cours d'algorithmique (1995)
(ISIA 3) Cours d'algorithmique (1995)(ISIA 3) Cours d'algorithmique (1995)
(ISIA 3) Cours d'algorithmique (1995)
Frank Nielsen
 
Unit 1 lesson 1
Unit 1 lesson 1Unit 1 lesson 1
Unit 1 lesson 1
tamma07
 
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Drumstick Bars Recipe
Drumstick Bars RecipeDrumstick Bars Recipe
Drumstick Bars Recipe
Kristy Kay
 
Minor Crimes Hurt Ambition by David Coolidge
Minor Crimes Hurt Ambition by David CoolidgeMinor Crimes Hurt Ambition by David Coolidge
Minor Crimes Hurt Ambition by David Coolidge
David Coolidge
 
Strategies for Education & Communicating with Parents
Strategies for Education & Communicating with Parents Strategies for Education & Communicating with Parents
Strategies for Education & Communicating with Parents
Jena Graham
 
@ut-of-the-Box™ 10 Steps Process
@ut-of-the-Box™ 10 Steps Process@ut-of-the-Box™ 10 Steps Process
@ut-of-the-Box™ 10 Steps Process
mcollaboration
 
2013年3月18日 日本国際保健医療学会 学生部会
2013年3月18日 日本国際保健医療学会 学生部会2013年3月18日 日本国際保健医療学会 学生部会
2013年3月18日 日本国際保健医療学会 学生部会
SUGAWARA, Hideyuki
 
Ad

Similar to (chapter 5) A Concise and Practical Introduction to Programming Algorithms in Java (20)

(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
(chapter 6) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 6) A Concise and Practical Introduction to Programming Algorithms in...(chapter 6) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 6) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
(chapter 9) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 9) A Concise and Practical Introduction to Programming Algorithms in...(chapter 9) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 9) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
(chapter 8) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 8) A Concise and Practical Introduction to Programming Algorithms in...(chapter 8) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 8) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Java introduction
Java introductionJava introduction
Java introduction
GaneshKumarKanthiah
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
ArthyR3
 
Learning core java
Learning core javaLearning core java
Learning core java
Abhay Bharti
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
ArthyR3
 
Ppt chapter09
Ppt chapter09Ppt chapter09
Ppt chapter09
Richard Styner
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
Rasan Samarasinghe
 
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptxJAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
fwzmypc2004
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.pptJAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
Edureka!
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
eMexo Technologies
 
slidlecturlecturlecturlecturlecturlecturlecturlectures06.ppt
slidlecturlecturlecturlecturlecturlecturlecturlectures06.pptslidlecturlecturlecturlecturlecturlecturlecturlectures06.ppt
slidlecturlecturlecturlecturlecturlecturlecturlectures06.ppt
KierenReynolds3
 
Arrays in Java Programming Language slides
Arrays in Java Programming Language slidesArrays in Java Programming Language slides
Arrays in Java Programming Language slides
ssuser5d6130
 
Java platform
Java platformJava platform
Java platform
Visithan
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed Overview
Buddha Tree
 
UNIT – 2 Features of java- (Shilpa R).pptx
UNIT – 2 Features of java- (Shilpa R).pptxUNIT – 2 Features of java- (Shilpa R).pptx
UNIT – 2 Features of java- (Shilpa R).pptx
shilpar780389
 
(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
(chapter 6) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 6) A Concise and Practical Introduction to Programming Algorithms in...(chapter 6) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 6) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
(chapter 9) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 9) A Concise and Practical Introduction to Programming Algorithms in...(chapter 9) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 9) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
(chapter 8) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 8) A Concise and Practical Introduction to Programming Algorithms in...(chapter 8) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 8) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
ArthyR3
 
Learning core java
Learning core javaLearning core java
Learning core java
Abhay Bharti
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
ArthyR3
 
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptxJAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
fwzmypc2004
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.pptJAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
Edureka!
 
slidlecturlecturlecturlecturlecturlecturlecturlectures06.ppt
slidlecturlecturlecturlecturlecturlecturlecturlectures06.pptslidlecturlecturlecturlecturlecturlecturlecturlectures06.ppt
slidlecturlecturlecturlecturlecturlecturlecturlectures06.ppt
KierenReynolds3
 
Arrays in Java Programming Language slides
Arrays in Java Programming Language slidesArrays in Java Programming Language slides
Arrays in Java Programming Language slides
ssuser5d6130
 
Java platform
Java platformJava platform
Java platform
Visithan
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed Overview
Buddha Tree
 
UNIT – 2 Features of java- (Shilpa R).pptx
UNIT – 2 Features of java- (Shilpa R).pptxUNIT – 2 Features of java- (Shilpa R).pptx
UNIT – 2 Features of java- (Shilpa R).pptx
shilpar780389
 
Ad

Recently uploaded (20)

Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdfHigh Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API CatalogMuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptxFIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptxFIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdfHigh Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API CatalogMuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptxFIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptxFIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 

(chapter 5) A Concise and Practical Introduction to Programming Algorithms in Java

  • 1. 1A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Frank NIELSEN [email protected] A Concise and Practical Introduction to Programming Algorithms in Java Chapter 5: Classes and objects
  • 2. 2A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen So far...: Executive summary ● Lecture 1: Variable, Expression, Assignment ● Lecture 2: Loops (for while do) Conditional structures (if else switch) Boolean predicate and connectors (|| &&) Loop escape break ● Lecture 3: functions (static) and recursion (terminal or not) ● Lecture 4: Objects
  • 3. 3A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Indenting source code (.java) ● Increase code readibility ● Avoid mistyping bugs (matching { }) Source code formatter, pretty printer, beautifier Different conventions are possible (but choose one) Implemented more or less in Software (S/W) Nedit, Jcreator, Jindent, etc...
  • 4. 4A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen http://java.sun.com/docs/codeconv/ Identing source code (.java) Examples for if else conditions
  • 5. 5A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Indenting source code (.java) http://java.sun.com/docs/codeconv/
  • 6. 6A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Indenting source code (.java) ● Bytecode size and indentation: Does not change fundamentally ● Bytecode is not human readable Demo Indent.java: notepad Jcreator & produced bytecode Indent.class open bytecode
  • 7. 7A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Identing source code (.java) Sometimes in Java code (Internet), comments include commands for generating automatically documentation by other tools: ... Like javadoc (paradigm literate programming, etc.) http://java.sun.com/j2se/javadoc/ La classe TC se trouve a: http://www.enseignement.polytechnique.fr/informatique/profs/Julien.Cervelle/TC/ Class TC
  • 8. 8A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions in Java ● Static functions that returns a type (eventually void) ● Functions are called inside the main procedure (or in other function body) ● Displaying and calling function are different (be not confused with SciLab or Maple System.out.println(function()); ● Java is a compiled OO language , not an interpreter
  • 9. 9A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions: void/display Java cannot cast void type into a String, so the compiler javac generates an error. (type checking) class Functions { static void PascalTriangle(int depth) {//... return ; } public static void main(String[] toto) { System.out.println(PascalTriangle(5)); } } 'void' type not allowed here'void' type not allowed here
  • 10. 10A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions: void/display Java is not an interpreter like SciLab or Maple Functions are called within a block of instructions... ... not in the console!!!!class Functions { static double f(double x) {return x;} static void main(String[] args) { } }
  • 11. 11A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Variables: static or not... Static variables are declared in the class bodyclass body class Toto { static int count1, count2; ... } Otherwise non-static variables (usual) are declared in function bodiesfunction bodies (main, etc.) public static void main(String[] args) {double x;int i;} ● Variables are kept in memory in their function scope {...} ● Static variables are kept in memory and can be shared by several functions...
  • 12. 12A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen class Functions { static int count1, count2; static void f1(){count1++;} static void f2(){count2++;} public static void main(String[] args) { count1=0; count2=0; for(int i=0;i<1000;i++) { double rand=Math.random(); if (rand<0.5) {f1();} else {f2();} } System.out.println("count1:"+count1); System.out.println("count2:"+count2); } } static or not...
  • 13. 13A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Java is pass by value ...and arrays and objects are pass by reference class BadSwap { static void swap(int arg1, int arg2) { int tmp; tmp=arg1; arg1=arg2; arg2=tmp; } public static void main(String[] toto) { int a=3; int b=2; System.out.println("a:"+a+" b:"+b); swap(a,b); System.out.println("After the swap..."); System.out.println("a:"+a+" b:"+b); } }
  • 14. 14A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Managing memory & functions When calling a function f, the current function (main) indicates .....where to write the value of the result To obtain the result, function f uses a local memory In that local memory, values of arguments are available //current function body {} int a=3,b=2; swap(a,b) Memory address main Value of a Value of b s w a p Value of arg1 Value of arg2 Value of tmp
  • 15. 15A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen static void swap(int arg1, int arg2) { int tmp; tmp=arg1; arg1=arg2; arg2=tmp; } public static void main(String[] toto) { int a=3; int b=2; swap(a,b); } Memory address main 3 2 1. Create memory for local variables of function main 2. Assign values for a and b b a
  • 16. 16A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen static void swap(int arg1, int arg2) { int tmp; tmp=arg1; arg1=arg2; arg2=tmp; } public static void main(String[] toto) { int a=3; int b=2; swap(a,b); } 3. create local space for function swap Memory address main 3 2 s w a p arg1 arg2 tmp b a
  • 17. 17A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen static void swap(int arg1, int arg2) { int tmp; // 0 is default value tmp=arg1; arg1=arg2; arg2=tmp; } public static void main(String[] toto) { int a=3; int b=2; swap(a,b); } 4. evaluate expression for getting values of arg1 and arg2 swap(a,b) becomes swap(3,2) Memory address main 3 2 s w a p arg1 arg2 tmp b a 3 2 0
  • 18. 18A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen static void swap(int arg1, int arg2) { int tmp; // 0 is default value tmp=arg1; arg1=arg2; arg2=tmp; } public static void main(String[] toto) { int a=3; int b=2; swap(a,b); } 5. Execute instruction tmp=arg1 Memory address main 3 2 s w a p arg1 arg2 tmp b a 3 2 3
  • 19. 19A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen static void swap(int arg1, int arg2) { int tmp; // 0 is default value tmp=arg1; arg1=arg2; arg2=tmp; } public static void main(String[] toto) { int a=3; int b=2; swap(a,b); } Memory address main 3 2 s w a p arg1 arg2 tmp b a 2 2 3 6. Execute instruction arg1=arg2
  • 20. 20A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen static void swap(int arg1, int arg2) { int tmp; // 0 is default value tmp=arg1; arg1=arg2; arg2=tmp; } public static void main(String[] toto) { int a=3; int b=2; swap(a,b); } Memory address main 3 2 s w a p arg1 arg2 tmp b a 2 3 3 7. Execute the sequence of instructions in the swap block Notice that here the swapped has been performed
  • 21. 21A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen static void swap(int arg1, int arg2) { int tmp; // 0 is default value tmp=arg1; arg1=arg2; arg2=tmp; } public static void main(String[] toto) { int a=3; int b=2; swap(a,b); } Memory address main 3 2 s w a p arg1 arg2 tmp b a 2 3 3 5. Execute the sequence of instructions in the swap block
  • 22. 22A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen static void swap(int arg1, int arg2) { int tmp; // 0 is default value tmp=arg1; arg1=arg2; arg2=tmp; // we omitted return ; } public static void main(String[] toto) { int a=3; int b=2; swap(a,b); } Memory address main 3 2 b a 8. Return result of function swap (here void!!!) 9. Release memory allocated for swap Variables a and b have kept their original values
  • 23. 23A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Memory for static variables class SwapStatic { static int a,b; static void swap() { ... } public static void main(String[] toto) { a=3; b=2; swap(); } } Memory address main 3 2 b a Memory for static variables of class SwapStatic swaptmp0
  • 24. 24A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen class SwapStatic { static int a,b; static void swap() { int tmp;// ok not to be static tmp=a; a=b; b=tmp; } public static void main(String[] toto) { a=3; b=2; System.out.println("a:"+a+" b:"+b); swap(); System.out.println("After the swap..."); System.out.println("a:"+a+" b:"+b); } } By passing using static
  • 25. 25A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Memory for arrays and pass by reference Arrays are allocated a continuous memory location for storing TYPE elements The value of the array variable is a reference to the beginning of the array Memory for arrays (heap) TypeElement [ ] tab= new TypeElement[size] tab[0] tab[1] tab[size-1] Array variable tab is a reference
  • 26. 26A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Memory management using new Type [] tab=new Type[Expression]; ● Evaluate Expression to get an integer value. ● Arrays are stored not in the local function memory, but rather in the global program memory: heap, tas en francais ● A cell (array element) in the heap (program memory) is accessible by any function which has as a local (non-static) variable a reference to the array.
  • 27. 27A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen class ArrayReference { public static void swap(int [] t, int i, int j) { int tmp; tmp=t[i]; t[i]=t[j]; t[j]=tmp; } public static void Display(int [] tab){... » public static void main(String[] args) { //int [] array=new int[10]; int [] array={0,1,2,3,4,5,6,7,8,9}; Display(array); swap(array,1,2); Display(array); } } 0 1 2 3 4 5 6 7 8 9 0 2 1 3 4 5 6 7 8 9
  • 28. 28A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Memory management using new 4 4 4 4 4 4 4 4 4 4 4 4 0 4 4 4 4 4 4 4 class BuildArray{ // Return a reference to an array public static int [] BuildArray(int size, int defaultval) { int [] result=new int[size]; for(int i=0;i<size;i++) result[i]=defaultval; return result; } public static void Zero(int[] tab, int pos) { tab[pos]=0; } public static void main(String [] argarray) { int v []=BuildArray(10,4); Display(v); Zero(v,2); Display(v); }
  • 29. 29A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Synopsis of this lecture ● Objects and records (fields, enregistrements) ● Object constructors ● Class type variables: References ● Functions on objects: Methods ● Array of objects ● Examples
  • 30. 30A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Why do we need objects? Java is an oriented-object (OO) programming language Encapsulate functions/data acting on a same domain For example, the String type Allows one to work on complex entities: Data structures For examples: ● Dates are triplets of numbers (MM/DD/YYYY) ● 2D point with co-ordinates (x,y) ● Student: Lastname, Firstname, Group, etc. These are called object records (fields)
  • 31. 31A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Declaring classes and objects ● Choose record/field names (enregistrement) ● Define a type of each record ● Similar to variables but without keyword static ● Class is then a new type with name... ... the class name
  • 32. 32A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Toy example public class Date { int dd; int mm; int yyyy; } Fields (champs/enregistrements) are also called object variables Do not have the leading keyword static Let day be a variable of type Date then day.dd day.mm dd.yyyy are variables of type int
  • 33. 33A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Toy example public class Student { String Lastname; String Firstname; int Company; double [ ] Marks; ... } Class Student encapsulates data attached to a student identity.
  • 34. 34A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Constructors To use an object, we first need to build it We construct an object using the instruction new But first, we need to define a constructor for the class A constructor is a method (non-static function) ... ...bearing the class' name This method does not return a result but assigns... ...values to the object's field Use this.field to access field of the object
  • 35. 35A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen public class Date { int dd; int mm; int yyyy; // Constructor public Date(int day, int month, int year) {this.dd=day; this.mm=month; this.yyyy=year;} } Constructors Date day=new Date(23,12,1971); Create an object of type Date
  • 36. 36A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen public class Date { int dd; int mm; int yyyy; public Date(int day, int month, int year) { this.dd=day; this.mm=month; this.yyyy=year; } } Public class YYY stored in YYY.java class TestDate{ public static void main(String args) { Date day=new Date(23,12,1971); } } Filename: Date.java Filename: TestDate.java
  • 37. 37A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Constructors ● Possibly several constructors (with different signatures) ● Best, to define a single one with all fields initialized ● Keyword this means the currently built object (not compulsory to write it explicitly but recommended) public Date(int day, int month, int year) {dd=day; this.mm=month; yyyy=year; } ● If no constructor is built, the system uses the by-default one (not recommended) Date day=new Date();// see poly pp. 59-61 day.yyyy=1971;
  • 38. 38A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen The null object ● This object is common to all classes ● Not possible to assign its fields ● Nor retrieve values of its fields, either (exception nullPointerException raised) ● Used for initializing a variable of type object: Student stud=null; ● It is often recommender to check if an object is null or not: if( stud!=null) stud.company=2;
  • 39. 39A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions/methods on objects Objects can be parameters of functions static TypeF F(Object1 obj1, ..., ObjectN objN) Functions may return an object as a result: static boolean isBefore (Date d1, Date d2) static Date readDate()
  • 40. 40A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Examplepublic class Date { int dd; int mm; int yyyy; public static final String[ ] months={ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; // Constructor public Date(int day, int month, int year) { this.dd=day; this.mm=month; this.yyyy=year; } }
  • 41. 41A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Example class TestDate{ static void Display(Date d){ System.out.println("The "+d.dd+" "+Date.months[d.mm- 1]+" of "+d.yyyy); } static boolean isBefore(Date d1, Date d2) { boolean result=true; if (d1.yyyy>d2.yyyy) result=false; if (d1.yyyy==d2.yyyy && d1.mm>d2.mm) result=false; if (d1.yyyy==d2.yyyy && d1.mm==d2.mm && d1.dd>d2.dd) result=false; return result; } public static void main(String[] args) { Date day1=new Date(23,12,1971); Display(day1); Date day2=new Date(23,6,1980); System.out.println(isBefore(day1,day2)); } }
  • 42. 42A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen class TestDate{ ... static Date lireDate() { int jj, mm, aaaa; System.out.println("Jour?"); jj=TC.lireInt(); System.out.println("Mois?"); mm=TC.lireInt(); System.out.println("Annee?"); aaaa=TC.lireInt(); Date day=new Date(jj,mm,aaaa); return day; } public static void main(String[] args) { Display(lireDate()); } }
  • 43. 43A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Variable of Type Object: Reference A variable of type Object is a reference on that object It stores the memory address of this referenced object Thus when we write: Date day1=new Date(23,12,1971); Date day2=day1; Display(day2); day2.mm=6; Display(day1); The date d1 is not copied, only the reference of... ...d1 is assigned to d2
  • 44. 44A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Copying objects... To copy (clone) an object to another we need to do it fieldwise // Two Scenarii: // day2 has already been created... day2.dd=day1.dd; day2.mm=day1.mm; day2.yyyy=day1.yyyy; // day2 object has not yet been created... static Date Copy(date day1) { Date newdate=new Date (day1.dd,day1.mm,day1.yyyy); return newdate; } ... Date d2=Copy(d1);
  • 45. 45A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Comparing two objects... Do not use == for object equality To compare objects, use a tailored predicate: static boolean isEqual(Date d1, Date d2) { return (d1.dd == d2.dd && d1.mm == d2.mm & d1.yyyy== d2.yyyy); }
  • 46. 46A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Comparing two objects... public static void main(String[] args) { Date day1=new Date(23,12,1971); Date day2=day1; // beware not copying here. Just memory reference Date day3=new Date(23,12,1971); System.out.println(isEqual(day1,day3)); System.out.println(day1); System.out.println(day2); System.out.println(day3); } Physical (memory) versus logical equality
  • 47. 47A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Array of objects ● Since classes defines new types... ... we can create array of objects ● To build an array of objects: new nameT[sizearray] Date [ ] tabDates=new Date[31]; ● When an array of object is built, the elements Date[i] are all initialized to the null object.
  • 48. 48A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Example public class Date { ... void Display() { System.out.println(dd+" "+months[mm-1]+" "+yyyy); } ... } public class XEvent { Date when; String what; public XEvent(Date d, String text) { this.when=d; this.what=text; } } Filename XEvent.java Filename Date.java
  • 49. 49A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen public class TestXEvent { public static void Display(XEvent e) { System.out.print(e.what+": "); e.when.Display(); } public static void main(String [] args) { Date d1=new Date(26,6,2008); XEvent e1=new XEvent(d1,"Birthday Julien"); Display(e1); XEvent [] tabEvent=new XEvent[5]; tabEvent[0]=e1; } }
  • 50. 50A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen public class TestXEvent {public static void Display(XEvent e) { System.out.print(e.what+": "); e.when.Display(); } public static boolean older(XEvent e1, XEvent e2) {return Date.isBefore(e1.when,e2.when);} public static XEvent oldest(XEvent[] tab) { XEvent result=tab[0]; for(int i=1;i<tab.length;++i) if (older(tab[i],result)) result=tab[i]; return result; } public static void main(String [] args) { Date d1=new Date(26,6,2003); XEvent e1=new XEvent(d1,"Birthday Julien"); Date d2=new Date(20,11,2000); XEvent e2=new XEvent(d2,"Birthday Audrey"); Date d3=new Date(23,6,1971); XEvent e3=new XEvent(d3,"Birthday Me"); Display(e1); XEvent [] tabEvent=new XEvent[3]; tabEvent[0]=e1;tabEvent[1]=e2;tabEvent[2]=e3; System.out.print("Oldest person::");Display(oldest(tabEvent)); } }
  • 51. 51A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Objects with array members Fields of objects may be arrays themselves always built with new Type[sizearray] // sizearray might be an expression, i.e., 3*n+2 It is not necessary at compile time to know statically... .... the array sizes class Polynome{ int degree; double [ ] coefficients; };
  • 52. 52A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Strings: Basic objects in Java ● A string of character is an object with type String ● A variable of type String is a reference on that object: String school= ''Ecole Polytechnique''; String vars=school; ● Once built, a string object cannot be modified ● Beware: use only for moderate length strings, otherwise use the class StringBuffer
  • 53. 53A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Class String: Some methods A method is a function or procedure on an object class Method Length() : gives the number of characters String s= ''anticonstitutionnellement''; System.out.println(s.length()); Method equals(): s1.equals(s2): Predicate that returns true if and only if the two strings s1 and s2 are made of the same sequence of characters. String s1=''Poincare''; String s2=TC.lireMotSuivant(); System.out.println(s1.equals(s2)); Beware: s1==s2 is different! It compares the reference of the strings. (Physical versus logical equality test)
  • 54. 54A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Class String in action...
  • 55. 55A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Class String: More methods Method charAt(): s.charAt(i) gives the character at the (i+1)th position in string s. String s= ''3.14159265''; System.out.println(s.charAt(1));
  • 56. 56A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Method compareTo(): u.compareTo(v) compares lexicographically the strings u with v. String u=''lien'', v=''lit'', w=''litterie''; System.out.println(u.compareTo(v)); System.out.println(v.compareTo(w)); http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html From Javadoc...
  • 57. 57A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Lexicographic total order on strings ● If there is a position k at which strings differ: this.charAt(k)-anotherString.charAt(k): String s1="Marin",s2="Martin"; // -11 from i to t int index=3;// meaning 4th pos System.out.println(s1.compareTo(s2)); System.out.println(s1.charAt(index)-s2.charAt(index)); ● else the difference of string lengths: this.length()-anotherString.length(): String s3="Bien",s4="Bienvenue"; System.out.println(s3.compareTo(s4)); System.out.println(s3.length()-s4.length());
  • 58. 58A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Class String: More methods
  • 59. 59A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Demystifying the main function class ClassName { public static void main(String[ ] args) { ... } } Function main has an array of string of characters as arguments These strings are stored in args[0], args[1], ... ... when calling java main s0 s1 s2 s3 Use Integer.parseInt() to convert a string into an integer
  • 60. 60A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Parsing arguments in the main function
  • 61. 61A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Parsing arguments in the main function
  • 62. 62A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen More evolved Java program skeleton... 2 versus (!=) 3 (2,1) (3,4) class Point { int x,y; Point(int xx, int yy){x=xx;y=yy;} public void Display() {System.out.println("("+x+","+y+")")} } // end of class Point class Skeleton { // Static class variables static int nbpoint=0; static double x; static boolean [] prime; static int f1(int p){return p/2;} static int f2(int p){return 2*p;} public static void main(String [] argArray) { System.out.println(f2(f1(3))+" versus (!=) "+f1(f2(3))); Point p,q; p=new Point(2,1); nbpoint++; q=new Point(3,4); nbpoint++; p.Display();q.Display(); } }
  • 63. 63A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen