Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:

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 C Programming
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.
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.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
Introduction to Computer Science One Dimensional Arrays Unit 9.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Fundamental Programming Structures in Java: Strings.
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Introduction to C Programming CE Lecture 9 Data Structures Arrays.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
 2006 Pearson Education, Inc. All rights reserved Arrays.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
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.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays Part 4.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
 Pearson Education, Inc. All rights reserved Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
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  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 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 Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
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.
Chapter 7: Characters, Strings, and the StringBuilder.
Arrays. 2 Till now we are able to declare and initialize few variables Reality: need to compute on a large amount of data Arrays are data structures that.
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.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
CS201 – Introduction to Computing – Sabancı University 1 Built-in Arrays l C++ native array type (not the class version) l Two versions ä fixed size arrays.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
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.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING 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.
Array contiguous memory locations that have the same name and type. Note: an array may contain primitive data BUT an array is a data structure a collection.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
 2005 Pearson Education, Inc. All rights reserved Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Array, Strings and Vectors
Primitive Types Vs. Reference Types, Strings, Enumerations
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
MSIS 655 Advanced Business Applications Programming
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples: int[] counts; double[] scores; String[] studentNames;

Array Allocation Arrays are allocated using the Java new operator The syntax is: new type[size]; Examples: counts = new int[10]; scores = new double[15]; studentNames = new String[10];

Array Organization counts Each box is an int variable The numbers on top are each variable’s subscript or index An array of size 10 has subscripts 0 to 9

Array Subscripts Arrays can contain any one type of value (either primitive values or references) Subscripts are used to access specific array values Examples: counts[0] // first variable in counts counts[1] // second variable in counts counts[9] // last variable in counts counts[10] // error – trying to access // variable outside counts

Expressions as Subscripts Array subscripts do not have to be constants Array subscripts do need to be integer expressions that evaluate to valid subscript values for the current array allocation Examples: counts[i] counts[2*i] counts[I/2]

Array Initialization Arrays can be initialized by giving a list of their elements If your list contains n elements the subscripts will range from 0 to n – 1 You do not need to allocate the array explicitly after it is initialized Example: int [] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

Initializing an Array of Strings final Sring[ ] NAME = { “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}; // procedure that prints the day of week public void printName (int day, OutputBox out) { out.print(NAME[day – 1]); }

Aliases It is possible to have two different variables refer to the same array When this happens these variables are called aliases Creating aliases is not a good programming practice Example of how it can happen: int [ ] A, B; … B = new int [10]; A = B;

Loops and Array Processing Initializes counts to 0, 10, 20, …, 90 for (int i=0; i < 10; i++) { counts[i] = i * 10; } Prints the contents of counts using length for (int i=0; i < counts.length; i++) { out.println(counts[i]); }

Extra Capacity Array Arrays cannot grow after they have been allocated You can allocate more space than you believe your application will need If you guess too low, you will still run out of space You do not need to use all the elements in an array (but total computer memory is finite)

Searching This loop terminates as soon as it finds the value 90 stored in grades bool found = false; int i = 0; while (i < size && !found) { // 90 is not in grades[0]..grades[i - 1] if (grades[i] == 90) found = true; else i++; }

Processing Parallel Arrays This loop counts the number of students whose performance improved from the first test to the second int improved = 0; for (int i = 0; i < size; i++) { if (grades1[i] < grades2[i]) improved++; }

Arrays of Objects Arrays of objects are declared in the same manner as arrays of primitive variables Assuming that a class Student was declared elsewhere a client application could declare and allocate an array of 10 students using Student[ ] students; students = new Student[10];

Passing Arrays as Arguments When an array is passed as an argument to a method, what is passed is a pointer to the array, not a new array (arrays are passed by reference) This means that if the method makes changes to the array, these changes are still in effect when the method returns to its caller This is not true for primitive values which are passed by value and not by reference Method header example: public void read(Student[ ] students) {

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

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}};

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];

Try: Write a program to Add two 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.

Introduction String manipulation is the most common operation performed in Java programs. The easiest way to represent a String (a sequence of characters) is by using an array of characters. –Example: –char place[] = new char[4]; –place[0] = ‘J’; –place[1] = ‘a’; –place[2] = ‘v’; –place[3] = ‘a’; Although character arrays have the advantage of being able to query their length, they themselves are too primitive and don’t support a range of common string operations. For example, copying a string, searching for specific pattern etc. Recognising the importance and common usage of String manipulation in large software projects, Java supports String as one of the fundamental data type at the language level. Strings related book keeping operations (e.g., end of string) are handled automatically.

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

String Class String class provides many operations for manipulating strings. –Constructors –Utility –Comparisons –Conversions String objects are read-only (immutable)

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();

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”};

String class - Constructors public String()Constructs an empty String. Public String(String value)Constructs a new string copying the specified string.

String – Some useful operations public int length()Returns the length of the string. public charAt(int index)Returns the character at the specified location (index) public int compareTo( String anotherString) public int compareToIgnoreCase( String anotherString) Compare the Strings. reigonMatch(int start, String other, int ostart, int count) Compares a region of the Strings with the specified start.

String – Some useful operations public String replace(char oldChar, char newChar) Returns a new string with all instances of the oldChar replaced with newChar. public trim()Trims leading and trailing white spaces. public String toLowerCase() public String toUpperCase() Changes as specified.

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()); }