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 4: Arrays and strings
2A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Why do we need arrays?
● To handle many variables at once
● Processing many data or generating many results
● In mathematics, we are familiar with variables
with indices:
In most languages, indices start at zero
(and not one).
...Just a convention
3A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Declaring arrays in Java
For a given type, TYPE[ ] is the type of arrays
storing elements of type TYPE.
● For arrays declared within the scope of functions:
● int [ ] x;
● boolean [ ] prime;
● double [ ] coordinates;
● float [ ] [ ] matrix;
● For arrays declared in the body of a class, use the keyword static:
(array variables can be used by any function of the class)
● static int [ ] x;
● static boolean [ ] prime;
4A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Building and initializing arrays
Observe:
static boolean prime[ ]={ false, true, true, true, false, true, false, true, false, false };
but not
static boolean prime[10]={ false, true, true, true, false, true, false, true, false, false };
5A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Building and initializing arrays
● Declare array with the reserved keyword new
● Specify the size of the array at built time
● Arrays can be declared and initialized at once too:
● int [ ] x;
● x=new int [32];
● boolean [ ] prime = new boolean[16];
● Arrays initialized by enumerating all its values:
int [ ] prime={2, 3, 5, 7, 11, 13, 17, 19};
6A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Size of arrays
Size of arrays is given by the member function length:
prime.length;
System.out.println(prime.length);
Size of arrays fixed for once, cannot be changed:
array.length=23; // Generate an error
7A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Size of arrays
8A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Index range of arrays and exceptions
Powerful mechanism of modern languages (Java, C++)
If index is out of range, an exception is raised on the fly:
ArrayIndexOutOfBounds
Out of range accesses may not be detected by the compiler:
Bug that yields termination or system crash
... However, fortunately, Java can catch exceptions too.
9A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Size of arrays cannot be modified
10A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Index range of arrays and exceptions
Observe the correct parsing
11A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
The concept of references
An array is allocated as a single contiguous memory block
Java is managing memory so you do not have to free it
once the array is not used anymore: garbage collector
An array variable is, in fact, a reference to the array
This reference of the array is the symbolic address of
the first element (index 0)
Thus, when we write...
int [ ] v = {0, 1, 2, 3, 4};
int [ ] t =v;
t[2]++;
System.out.println(t[2]++);
... the elements of the array v are not copied verbatim to t. Only the reference!!!
12A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Arrays & references
13A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions & arrays
Functions and procedures can have arrays as arguments.
(remember that array types are: TypeElement[ ])
Example: Function that returns the minimum of an array of integers
14A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions & arrays
Example: Function that returns the inner product of 2 vectors
(produit scalaire)
15A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Array arguments in functions
A variable that has a type array is a reference to the array
(the memory address of the first element)
Therefore an argument of type array does not copy
all array elements in the memory allocated for the function,
but rather allocate a single memory reference:
a machine word.
static void MyFunction(int [ ] x)
MyFunction(v);
Only the reference of v is copied to the memory allocated for
the function MyFunction.
16A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Array arguments in functions
Thus we can modify the inside a function the contents of
the array: the values of the elements of the array.
17A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions returning an array
18A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Arrays of arrays...
So far, we described linear array (1D).
What about matrices (2D arrays)?
A bidimensional array (n,m) consists of n lines,
each of which is an array of m elements
int [ ] [ ] matrix;
matrix=new int[n][m];
By default, at initialization, the array is filled up with zero
Change the contents of 2D arrays using 2 nested loops:
for(int i=0; i<n; i++)
for(int j=0; j<m;j++)
matrix[i][j]=i*j+1;
19A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
2D Arrays: Matrix x vector product
20A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Dichotomic search
Also called binary search algorithm
Assume we are given a sorted array of size n:
array[0] < array[1] < ... < array[n-1]
and a query key p
Seek whether there is an element in the array that has value p
That is, give a function that return the index of the element in
the array with value p, or that returns -1 otherwise.
21A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Dichotomic search: Think recursion!
● Start with a search interval [left, right] with left=0 and right=n-1
● Let m denote the middle of this interval: m=(left+right)/2
● If array[m]=p then we are done, and we return m;
● If array[m] <a, then if the solution exists it is in [m+1,right]
● If array[m]>a, then if the solution exists it is in [left,m+1]
● The search algorithm terminates if left>right, we return -1;
22A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Dichotomic search: Recursion
23A 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
24A 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)
25A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Class String in action...
26A 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));
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));
27A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Class String: More methods
28A 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
29A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Parsing arguments in the main function
30A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Parsing arguments in the main function
31A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen

More Related Content

What's hot (20)

Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Scala functions
Scala functionsScala functions
Scala functions
Knoldus Inc.
 
Basics of matlab
Basics of matlabBasics of matlab
Basics of matlab
Anil Maurya
 
Matlab solved problems
Matlab solved problemsMatlab solved problems
Matlab solved problems
Make Mannan
 
Matlab1
Matlab1Matlab1
Matlab1
guest8ba004
 
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
Muhammad Rizwan
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab Overviiew
Nazim Naeem
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
Praveen M Jigajinni
 
(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
 
Linear Convolution using Matlab Code
Linear Convolution  using Matlab CodeLinear Convolution  using Matlab Code
Linear Convolution using Matlab Code
Bharti Airtel Ltd.
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
Praveen M Jigajinni
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
Mohan Raj
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
Angelo Corsaro
 
Imp_Points_Scala
Imp_Points_ScalaImp_Points_Scala
Imp_Points_Scala
Nagavarunkumar Kolla
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
Angelo Corsaro
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
Angelo Corsaro
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scripts
Ameen San
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
Dhammpal Ramtake
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Basics of matlab
Basics of matlabBasics of matlab
Basics of matlab
Anil Maurya
 
Matlab solved problems
Matlab solved problemsMatlab solved problems
Matlab solved problems
Make Mannan
 
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab Overviiew
Nazim Naeem
 
(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
 
Linear Convolution using Matlab Code
Linear Convolution  using Matlab CodeLinear Convolution  using Matlab Code
Linear Convolution using Matlab Code
Bharti Airtel Ltd.
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
Mohan Raj
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
Angelo Corsaro
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
Angelo Corsaro
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
Angelo Corsaro
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scripts
Ameen San
 

Viewers also liked (19)

(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 1l 3
Unit 1l 3Unit 1l 3
Unit 1l 3
tamma07
 
Game
GameGame
Game
tamma07
 
Slides: The dual Voronoi diagrams with respect to representational Bregman di...
Slides: The dual Voronoi diagrams with respect to representational Bregman di...Slides: The dual Voronoi diagrams with respect to representational Bregman di...
Slides: The dual Voronoi diagrams with respect to representational Bregman di...
Frank Nielsen
 
(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
 
(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
 
Audience research results and conclusions
Audience research  results and conclusionsAudience research  results and conclusions
Audience research results and conclusions
gryall97
 
Crohns and IBS Conditions - 03112014
Crohns and IBS Conditions - 03112014 Crohns and IBS Conditions - 03112014
Crohns and IBS Conditions - 03112014
MemberEducation
 
Open house nov 7 2013 m&m team
Open house nov 7 2013 m&m teamOpen house nov 7 2013 m&m team
Open house nov 7 2013 m&m team
MemberEducation
 
2013年3月18日 日本国際保健医療学会 学生部会
2013年3月18日 日本国際保健医療学会 学生部会2013年3月18日 日本国際保健医療学会 学生部会
2013年3月18日 日本国際保健医療学会 学生部会
SUGAWARA, Hideyuki
 
Biz op 30 min nov 9 2013
Biz op 30 min nov 9 2013Biz op 30 min nov 9 2013
Biz op 30 min nov 9 2013
MemberEducation
 
Interactive media
Interactive mediaInteractive media
Interactive media
idil moali
 
Photographic imaging
Photographic imagingPhotographic imaging
Photographic imaging
idil moali
 
Tv commercials
Tv commercialsTv commercials
Tv commercials
idil moali
 
Screenshot process of front cover
Screenshot process of front coverScreenshot process of front cover
Screenshot process of front cover
gryall97
 
Your customers deserve data driven communications, Communicator Corp
Your customers deserve data driven communications, Communicator CorpYour customers deserve data driven communications, Communicator Corp
Your customers deserve data driven communications, Communicator Corp
Internet World
 
Commercial radio
Commercial radioCommercial radio
Commercial radio
idil moali
 
Student-Produced Event Broadcasting
Student-Produced Event BroadcastingStudent-Produced Event Broadcasting
Student-Produced Event Broadcasting
Jena Graham
 
(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 1l 3
Unit 1l 3Unit 1l 3
Unit 1l 3
tamma07
 
Slides: The dual Voronoi diagrams with respect to representational Bregman di...
Slides: The dual Voronoi diagrams with respect to representational Bregman di...Slides: The dual Voronoi diagrams with respect to representational Bregman di...
Slides: The dual Voronoi diagrams with respect to representational Bregman di...
Frank Nielsen
 
(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
 
(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
 
Audience research results and conclusions
Audience research  results and conclusionsAudience research  results and conclusions
Audience research results and conclusions
gryall97
 
Crohns and IBS Conditions - 03112014
Crohns and IBS Conditions - 03112014 Crohns and IBS Conditions - 03112014
Crohns and IBS Conditions - 03112014
MemberEducation
 
Open house nov 7 2013 m&m team
Open house nov 7 2013 m&m teamOpen house nov 7 2013 m&m team
Open house nov 7 2013 m&m team
MemberEducation
 
2013年3月18日 日本国際保健医療学会 学生部会
2013年3月18日 日本国際保健医療学会 学生部会2013年3月18日 日本国際保健医療学会 学生部会
2013年3月18日 日本国際保健医療学会 学生部会
SUGAWARA, Hideyuki
 
Biz op 30 min nov 9 2013
Biz op 30 min nov 9 2013Biz op 30 min nov 9 2013
Biz op 30 min nov 9 2013
MemberEducation
 
Interactive media
Interactive mediaInteractive media
Interactive media
idil moali
 
Photographic imaging
Photographic imagingPhotographic imaging
Photographic imaging
idil moali
 
Tv commercials
Tv commercialsTv commercials
Tv commercials
idil moali
 
Screenshot process of front cover
Screenshot process of front coverScreenshot process of front cover
Screenshot process of front cover
gryall97
 
Your customers deserve data driven communications, Communicator Corp
Your customers deserve data driven communications, Communicator CorpYour customers deserve data driven communications, Communicator Corp
Your customers deserve data driven communications, Communicator Corp
Internet World
 
Commercial radio
Commercial radioCommercial radio
Commercial radio
idil moali
 
Student-Produced Event Broadcasting
Student-Produced Event BroadcastingStudent-Produced Event Broadcasting
Student-Produced Event Broadcasting
Jena Graham
 
Ad

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

(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) 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
 
Week06
Week06Week06
Week06
hccit
 
(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
 
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
 
Ppt chapter09
Ppt chapter09Ppt chapter09
Ppt chapter09
Richard Styner
 
(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
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
dplunkett
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Array.ppt
Array.pptArray.ppt
Array.ppt
SbsOmit1
 
array.ppt
array.pptarray.ppt
array.ppt
rajput0302
 
Java™ (OOP) - Chapter 7: "Multidimensional Arrays"
Java™ (OOP) - Chapter 7: "Multidimensional Arrays"Java™ (OOP) - Chapter 7: "Multidimensional Arrays"
Java™ (OOP) - Chapter 7: "Multidimensional Arrays"
Gouda Mando
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
Pamarthi Kumar
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
raksharao
 
Arrays in JAVA.ppt
Arrays in JAVA.pptArrays in JAVA.ppt
Arrays in JAVA.ppt
SeethaDinesh
 
Java arrays
Java    arraysJava    arrays
Java arrays
Mohammed Sikander
 
JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.ppt
MohammedNouh7
 
Upstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - ArraysUpstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - Arrays
DanWooster1
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) 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
 
Week06
Week06Week06
Week06
hccit
 
(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
 
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
 
(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
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
dplunkett
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Java™ (OOP) - Chapter 7: "Multidimensional Arrays"
Java™ (OOP) - Chapter 7: "Multidimensional Arrays"Java™ (OOP) - Chapter 7: "Multidimensional Arrays"
Java™ (OOP) - Chapter 7: "Multidimensional Arrays"
Gouda Mando
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
Pamarthi Kumar
 
Arrays in JAVA.ppt
Arrays in JAVA.pptArrays in JAVA.ppt
Arrays in JAVA.ppt
SeethaDinesh
 
JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.ppt
MohammedNouh7
 
Upstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - ArraysUpstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - Arrays
DanWooster1
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Ad

Recently uploaded (20)

Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
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
 
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
 
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
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
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
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
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
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
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
 
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
 
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
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
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
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
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
 

(chapter 4) 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 4: Arrays and strings
  • 2. 2A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Why do we need arrays? ● To handle many variables at once ● Processing many data or generating many results ● In mathematics, we are familiar with variables with indices: In most languages, indices start at zero (and not one). ...Just a convention
  • 3. 3A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Declaring arrays in Java For a given type, TYPE[ ] is the type of arrays storing elements of type TYPE. ● For arrays declared within the scope of functions: ● int [ ] x; ● boolean [ ] prime; ● double [ ] coordinates; ● float [ ] [ ] matrix; ● For arrays declared in the body of a class, use the keyword static: (array variables can be used by any function of the class) ● static int [ ] x; ● static boolean [ ] prime;
  • 4. 4A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Building and initializing arrays Observe: static boolean prime[ ]={ false, true, true, true, false, true, false, true, false, false }; but not static boolean prime[10]={ false, true, true, true, false, true, false, true, false, false };
  • 5. 5A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Building and initializing arrays ● Declare array with the reserved keyword new ● Specify the size of the array at built time ● Arrays can be declared and initialized at once too: ● int [ ] x; ● x=new int [32]; ● boolean [ ] prime = new boolean[16]; ● Arrays initialized by enumerating all its values: int [ ] prime={2, 3, 5, 7, 11, 13, 17, 19};
  • 6. 6A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Size of arrays Size of arrays is given by the member function length: prime.length; System.out.println(prime.length); Size of arrays fixed for once, cannot be changed: array.length=23; // Generate an error
  • 7. 7A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Size of arrays
  • 8. 8A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Index range of arrays and exceptions Powerful mechanism of modern languages (Java, C++) If index is out of range, an exception is raised on the fly: ArrayIndexOutOfBounds Out of range accesses may not be detected by the compiler: Bug that yields termination or system crash ... However, fortunately, Java can catch exceptions too.
  • 9. 9A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Size of arrays cannot be modified
  • 10. 10A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Index range of arrays and exceptions Observe the correct parsing
  • 11. 11A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen The concept of references An array is allocated as a single contiguous memory block Java is managing memory so you do not have to free it once the array is not used anymore: garbage collector An array variable is, in fact, a reference to the array This reference of the array is the symbolic address of the first element (index 0) Thus, when we write... int [ ] v = {0, 1, 2, 3, 4}; int [ ] t =v; t[2]++; System.out.println(t[2]++); ... the elements of the array v are not copied verbatim to t. Only the reference!!!
  • 12. 12A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Arrays & references
  • 13. 13A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions & arrays Functions and procedures can have arrays as arguments. (remember that array types are: TypeElement[ ]) Example: Function that returns the minimum of an array of integers
  • 14. 14A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions & arrays Example: Function that returns the inner product of 2 vectors (produit scalaire)
  • 15. 15A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Array arguments in functions A variable that has a type array is a reference to the array (the memory address of the first element) Therefore an argument of type array does not copy all array elements in the memory allocated for the function, but rather allocate a single memory reference: a machine word. static void MyFunction(int [ ] x) MyFunction(v); Only the reference of v is copied to the memory allocated for the function MyFunction.
  • 16. 16A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Array arguments in functions Thus we can modify the inside a function the contents of the array: the values of the elements of the array.
  • 17. 17A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions returning an array
  • 18. 18A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Arrays of arrays... So far, we described linear array (1D). What about matrices (2D arrays)? A bidimensional array (n,m) consists of n lines, each of which is an array of m elements int [ ] [ ] matrix; matrix=new int[n][m]; By default, at initialization, the array is filled up with zero Change the contents of 2D arrays using 2 nested loops: for(int i=0; i<n; i++) for(int j=0; j<m;j++) matrix[i][j]=i*j+1;
  • 19. 19A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen 2D Arrays: Matrix x vector product
  • 20. 20A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Dichotomic search Also called binary search algorithm Assume we are given a sorted array of size n: array[0] < array[1] < ... < array[n-1] and a query key p Seek whether there is an element in the array that has value p That is, give a function that return the index of the element in the array with value p, or that returns -1 otherwise.
  • 21. 21A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Dichotomic search: Think recursion! ● Start with a search interval [left, right] with left=0 and right=n-1 ● Let m denote the middle of this interval: m=(left+right)/2 ● If array[m]=p then we are done, and we return m; ● If array[m] <a, then if the solution exists it is in [m+1,right] ● If array[m]>a, then if the solution exists it is in [left,m+1] ● The search algorithm terminates if left>right, we return -1;
  • 22. 22A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Dichotomic search: Recursion
  • 23. 23A 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
  • 24. 24A 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)
  • 25. 25A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Class String in action...
  • 26. 26A 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)); 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));
  • 27. 27A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Class String: More methods
  • 28. 28A 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
  • 29. 29A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Parsing arguments in the main function
  • 30. 30A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Parsing arguments in the main function
  • 31. 31A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen