1 Chapter 4: Arrays and strings Taufik Djatna

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Arrays Liang, Chpt 5. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Fundamental Programming Structures in Java: Strings.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
MT311 Java Application Programming and Programming Languages Li Tak Sing ( 李德成 )
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Computer Science 210 Computer Organization Arrays.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Chapter 8: Arrays.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Introduction to Java Java Translation Program Structure
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
Array Objectives To understand the concept of arrays To understand the purpose to which we use arrays. To be able to declare references to arrays. To be.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Java Part I By Wen Fei, HAO. Program Structure public class ClassName { public static void main(String[] args) { program statements } user defined methods.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
C LANGUAGE UNIT 3. UNIT 3 Arrays Arrays – The concept of array – Defining arrays – Initializing arrays.
1 A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Frank NIELSEN A Concise and.
Information and Computer Sciences University of Hawaii, Manoa
Java Review: Reference Types
An Introduction to Java – Part I, language basics
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Introduction to java Part I By Shenglan Zhang.
Presentation transcript:

1 Chapter 4: Arrays and strings Taufik Djatna

2 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 Declaring arrays in Java For a given type, TYPE[ ] is the type of arrays storing elements of type TYPE. 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; ● 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 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 }; 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 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}; ● 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 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 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 Size of arrays

8 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. 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 Size of arrays cannot be modified

10 Index range of arrays and exceptions Observe the correct parsing

11 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!!! 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 Arrays & references

13 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 Functions & arrays Example: Function that returns the inner product of 2 vectors (produit scalaire)

15 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 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 Functions returning an array

18 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 2D Arrays: Matrix x vector product

20 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 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 Dichotomic search: Recursion

23 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= ‘Dept TIN IPB''; String vars=school; ● Once built, a string object cannot be modified ● Beware: use only for moderate length strings, otherwise use the class StringBuffer

24 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 Class String in action...

26 Class String: More methods Method charAt(): s.charAt(i) gives the character at the (i+1)th position in string s. String s= '' ''; 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 Class String: More methods

28 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 Parsing arguments in the main function

30 Parsing arguments in the main function

31 Thank You