1 Unit-2 Arrays, Strings and Collections. 2 Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used.

Slides:



Advertisements
Similar presentations
1 Arrays, Strings and Collections [1] Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering.
Advertisements

Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
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.
Java Programming Strings Chapter 7.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
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.
Chapter 10.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Fundamental Programming Structures in Java: Strings.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Strings Edward J. Biebel. Strings Strings are fundamental part of all computing languages. At the basic level, they are just a data structure that can.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
Java Unit 9: Arrays Declaring and Processing Arrays.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
1 Lecture # 4. * An array is a group of contiguous or related data items that share a common name. * Each value is stored at a specific position * Position.
ArrayList, Multidimensional Arrays
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
String Manipulation. Java String class  The String class represents character strings “Tammy Bailey”  All strings (arrays of characters) in Java programs.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Data Structures and Algorithms Lecture 1 Instructor: Quratulain Date: 1 st Sep, 2009.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Chapter 7: Characters, Strings, and the StringBuilder.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
String Handling StringBuffer class character class StringTokenizer class.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
Variables and Strings. Variables  When we are writing programs, we will frequently have to remember a value for later use  We will want to give this.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
17-Feb-16 String and StringBuilder Part I: String.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Arrays in java Unit-1 Introduction to Java. Array There are situations where we might wish to store a group of similar type of values in a variable. Array.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
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.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
Chapter 9 Introduction to Arrays Fundamentals of Java.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Computer Programming BCT 1113
Array, Strings and Vectors
Fifth Lecture Arrays and Lists
String and String Buffers
Modern Programming Tools And Techniques-I Lecture 11: String Handling
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
Introduction To Programming Information Technology , 1’st Semester
MSIS 655 Advanced Business Applications Programming
Lecture 07 String Jaeki Song.
Arrays Week 2.
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
String Class.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

1 Unit-2 Arrays, Strings and Collections

2 Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used when programs have to handle large amount of data Each value is stored at a specific position Position is called a index or superscript. Base index = 0 The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, a loop with index as the control variable can be used to read the entire array, perform calculations, and print out the results.

3 Arrays - Introduction index values

4 Like any other variables, arrays must declared and created before they can be used. Creation of arrays involve three steps: Declare the array Create storage area in primary memory. Put values into the array (i.e., Memory location) Declaration of Arrays: Form 1: Type arrayname[] Form 2: Type [] arrayname; Examples: int[] students; int students[]; Note: we don’t specify the size of arrays in the declaration. Declaration of Arrays

5 Creation of Arrays After declaring arrays, we need to allocate memory for storage array items. In Java, this is carried out by using “new” operator, as follows: Arrayname = new type[size]; Examples: students = new int[7];

6 Initialisation of Arrays Once arrays are created, they need to be initialised with some values before access their content. A general form of initialisation is: Arrayname [index/subscript] = value; Example: students[0] = 50; students[1] = 40; Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified. Unlike C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will generate an error message.

7 Arrays are fixed length Length is specified at create time In java, all arrays store the allocated size in a variable named “length”. We can access the length of arrays as arrayName.length: e.g. int x = students.length; // x = 7 Accessed using the index e.g. int x = students [1]; // x = 40 Arrays – Length

8 Arrays – Example // StudentArray.java: store integers in arrays and access public class StudentArray{ public static void main(String[] args) { int[] students; students = new int[7]; System.out.println("Array Length = " + students.length); for ( int i=0; i < students.length; i++) students[i] = 2*i; System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); } :w

9 Arrays can also be initialised like standard variables at the time of their declaration. Type arrayname[] = {list of values}; Example: int[] students = {55, 69, 70, 30, 80}; Creates and initializes the array of integers of length 5. In this case it is not necessary to use the new operator. Arrays – Initializing at Declaration

10 Arrays – Example // StudentArray.java: store integers in arrays and access public class StudentArray{ public static void main(String[] args) { int[] students = {55, 69, 70, 30, 80}; System.out.println("Array Length = " + students.length); System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); }

11 Two Dimensional Arrays Two dimensional arrays allows us to store data that are recorded in table. For example: Table contains 12 items, we can think of this as a matrix consisting of 4 rows and 3 columns. Item1Item2Item3 Salesgirl # Salesgirl # Salesgirl # Salesgirl # Sold Person

12 2D arrays manipulations Declaration: int myArray [][]; Creation: myArray = new int[4][3]; // OR int myArray [][] = new int[4][3]; Initialisation: Single Value; myArray[0][0] = 10; Multiple values: int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; int tableA[][] = {{10, 15, 30}, {14, 30, 33}};

13 Variable Size Arrays Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows: int a[][] = new int [3][]; a[0]= new int [3]; a[1]= new int [2]; a[2]= new int [4];

14 Try: Write a program to Add to Matrix Define 2 dimensional matrix variables: Say: int a[][], b[][]; Define their size to be 2x3 Initialise like some values Create a matrix c to storage sum value c[0][0] = a[0][0] + b[0][0] Print the contents of result matrix.

15 Create the Circle objects and stores them in the array. //declare an array for Circle Circle circleArray[] = new Circle[25]; int r = 0; // create circle objects and store in array for (r=0; r <25; r++) circleArray[r] = new Circle(r); Arrays of Objects

16 String Operations in Java

Strings  Strings are fundamental part of all computing languages.  At the basic level, they are just a data structure that can hold a series of characters  However, strings are not implemented as a character array in Java as in other languages.

18 String Operations in Java Following are some useful classes that Java provides for String operations. String Class StringBuffer Class StringTokenizer Class

19 Strings Basics Declaration and Creation: String stringName; stringName = new String (“string value”); Example: String city; city = new String (“Bangalore”); Length of string can be accessed by invoking length() method defined in String class: int len = city.length();

Strings in Java Strings are implemented as two classes in Java java.lang.String provides an unchangeable String object java.lang.StringBuffer provides a String object that can be amended

21 String operations and Arrays Java Strings can be concatenated using the + operator. String city = “New” + “York”; String city1 = “Delhi”; String city2 = “New “+city1; Strings Arrays String city[] = new String[5]; city[0] = new String(“Melbourne”); city[1] = new String(“Sydney”); … String megacities[] = {“Brisbane”, “Sydney”, “Melbourne”, “Adelaide”, “Perth”};

Basic String Methods length() returns the length of the string toLowerCase() converts the string to lower case toUpperCase() converts the string to upper case replace(char, char) replaces occurrences of one character with another character

Basic Strings continued Basic strings are not meant to change frequently so there are no add or append methods However the concat(String) method does allow two strings to be concatenated together

Basic Strings continued Substrings of a String object can also be accessed A portion of String object can be copied to a character array using the getChars() method The substring() method can return substring beginning at a specified offset

Searching a string Methods for searching strings indexOf(‘x’ ) searches for the first occurrence of x indexOf(x, y) searches for the first occurrence of x after the offset of y lastIndexOf(x) searches backwards for the first occurrence of x lastIndexOf(x, y) searches backwards for the first occurrence of x after the offset of y

26 String Class - example // StringDemo.java: some operations on strings class StringDemo { public static void main(String[] args) { String s = new String("Have a nice Day"); // String Length = 15 System.out.println("String Length = " + s.length() ); // Modified String = Have a Good Day System.out.println("Modified String = " + s.replace('n', 'N')); // Converted to Uppercse = HAVE A NICE DAY" System.out.println("Converted to Uppercase = " + s.toUpperCase()); // Converted to Lowercase = have a nice day" System.out.println("Converted to Lowercase = " + s.toLowerCase()); }

27 StringDemo Output java StringDemo String Length = 15 Modified String = Have a Nice Day Converted to Uppercase = HAVE A NICE DAY Converted to Lowercase = have a nice day

StringBuffer class  The StringBuffer class is provided for strings that need may need to be changed  While String creates of fixed length, StringBuffer creates strings of flexible length that can modified in terms of both length and content.  The StringBuffer class contains methods for both inserting and appending text  An object created as a StringBuffer can easily be converted to an object of the String class if needed

More on StringBuffer Class Conversion may be needed because many Java library methods expect a string The toString() method is used for converting a StringBuffer object to a String object Example of converting a StringBuffer to a String: public void paint(Graphics g) { StringBuffer buf = new StringBuffer("Hello, World"); g.drawString(buf.toString(), 10, 10); }

More on StringBuffer Class StringBuffer objects are mutable and capacity & length affect performance If the StringBuffer object needs to be expanded during an append or insert, a new array is created and the old data copied to it Use capacity() and ensureCapacity(int) methods to minimize expansions

Length v. Capacity The length() method returns the length of the string in the StringBuffer The capacity() method returns the total “space” in a StringBuffer The ensureCapacity(int) method insures the StringBuffer has at least the specified amount of capacity remaining

Length v. Capacity con ’ t Examples of length() and capacity() methods StringBuffer buf = new StringBuffer(25);// creates StringBuffer with length 25 buf.append("13 Characters"); // appends 13 characters int len = buf.length(); // length() returns 13 int cap = buf.capacity(); // capacity returns 25

33 Summary Arrays allows grouping of sequence of related items. Java supports powerful features for declaring, creating, and manipulating arrays in efficient ways. Each items of arrays of arrays can have same or variable size. Java provides enhanced support for manipulating strings and manipulating them appears similar to manipulating standard data type variables.