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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Arrays, A1 COMP 401, Fall 2014 Lecture 4 8/28/2014.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
©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.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Java Syntax Primitive data types Operators Control statements.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Fundamental Programming Structures in Java: Strings.
JavaScript, Third Edition
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.
03/16/ What is an Array?... An array is an object that stores list of items. Each slot of an array holds an individual element. Characteristics.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
1 Chapter 4: Arrays and strings Taufik Djatna
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
From C++ to Java A whirlwind tour of Java for C++ programmers.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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 BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Introduction to Collections Arrays. Collections Collections allow us to treat a group of values as one collective entity. The array is a collection of.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
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.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
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.
Chapter 7: Characters, Strings, and the StringBuilder.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
Interfaces and Inner Classes
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
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.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
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.
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
Chapter 2 Reference Types. Class : Point2D class Point2D { private double x,y; public Point2D(double xx,double yy) { x = xx ; y = yy ;} public void setX(double.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
ARRAYS Multidimensional realities Image courtesy of
 2005 Pearson Education, Inc. All rights reserved Arrays.
Object Oriented Programming Lecture 2: BallWorld.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
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.
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. For example,
Chapter VII: Arrays.
Information and Computer Sciences University of Hawaii, Manoa
Array, Strings and Vectors
String class.
Selenium WebDriver Web Test Tool Training
String Handling in JAVA
Java Review: Reference Types
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. Every time.
Presentation transcript:

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 and some of its  methods in Arrays. 

 Although we haven't yet discussed classes and objects, recall from Chapter 4, the String class.  1. String objects are handled specially by the compiler.  String is the only class which has "implicit" instantiation.  2. The String class is defined in the java.lang package.  3. Strings are immutable. The value of a String object can  never be changed.  4. For mutable Strings, use the StringBuffer class, which we  will cover in Semester 2, “Advanced Topics in Java”. Brief Review of the String Class

 Normally, objects in Java are created with the new keyword.  However, String objects can be created "implicitly":  Strings can also be created using the + operator. The + operator, when applied to Strings means concatenation. Creating String Objects String name; name = new String("Craig"); String name; name = "Craig"; int age = 21; String message = "Craig wishes he was " + age + " years old";

 The String class has many methods. The most commonly used are:  length() - returns the number of characters in the String  charAt() - returns the character at the specified index  equals() - returns true if two strings have equal contents  compareTo() -returns 0 if equal, -# if one String is "less than” the other, +# if one String is "greater than" the the other.  indexOf() - returns the index of specified String or character  substring() -returns a portion of the String's text  toUpperCase(), toLowerCase() - converts the String to upper or lower case characters Commonly used String methods

String Examples String name = "Craig"; String name2 = "Craig"; if (name.equals(name2)) System.out.println("The names are the same"); String name = "Craig Schock"; int lastNameIndex = name.indexOf("Schock"); String grade = "B+"; double gpa = 0.0; if (grade.charAt(0) == 'B') gpa = 3.0; if (grade.charAt(1) == '+') gpa = gpa + 0.3;

Important note: The == operator cannot be used to test String objects for equality Variables of type String are references to objects (ie. memory addresses) Comparing two String objects using == actually compares their memory addresses. Two separate String objects may contain the equivalent text, but reside at different memory locations. Use the equals method to test for equality. Testing Strings for Equality

 Java supports arrays  An array is a collection of elements where each element is the same type.  Element type can be primitive or Object  Each element is a single value  The length of the array is set when it is created. It cannot change.  Individual array elements are accessed via an index.  Array index numbering starts at 0.  Note: Some references claim that arrays in Java are Objects. THIS IS NOT TRUE.  Arrays do exhibit some behaviour which is similar to objects, but they are not themselves, objects. Arrays in Java

 Creating an array is a 2 step process  It must be declared (declaration does not specify size)  It must be created (ie. memory must be allocated for the array) Creating Arrays type[] arrayName; declaration syntax: note the location of the [] int[] grades;// declaration grades = new int[5];// Create array. // specify size // assign new array to // array variable

int[] grades = new int[5];  When an array is created, all of its elements are automatically initialized  0 for integral types  0.0 for floating point types  false for boolean types  null for object types Creating Arrays array indices Note: maximum array index is length -1 grades

 Because array elements are initialized to 0, the array should be initialized with usable values before the array is used.  This can be done with a loop  Arrays have a length attribute which can be used for bounds checking  Elements are accessed using an index and [] Initializing and Using Arrays int[] sequence = new int[5]; for (int i=0; i< sequence.length; i++) { sequence[i] = i * 25; } array length: ensures loop won't go past end of the array Array element being accessed. In this case, it is being assigned a value.

 Another way of initializing lists is by using initializer lists.  The array is automatically created  The array size is computed from the number of items in the list. Using initializer lists int[] grades = {100, 96, 78, 86, 93}; type[] arrayName = {initializer_list}; String[] colours = {"Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};

 Whenever and array is accessed, the index is checked to ensure that it within the bounds of the array.  Attempts to access an array element outside the bounds of the array will cause an ArrayIndexOutOfBounds exception to be thrown. Array Bounds Checking int[] sequence = new int[5]; sequence[0] = 50;// ok sequence[1] = 60;// ok sequence[-1] = 100;// Exception sequence[5] = 30;// Exception

 You may recall that the main method takes an array of String objects as a parameter.  This array of Strings holds the command line parameters which were passed to the java program when it was started The main() method public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } Array holding command line parameters

Command line parameters args java HelloWorld This is a test, Jim This is Jim a test, name of class containing the main() method

 Arrays with multiple dimensions can also be created.  They are created and initialized in the same way as single dimensioned arrays. Multi-dimensional Arrays type[][] arrayName; declaration syntax: each [] indicates another dimension int[][] grades = new int[20][5]; for(int i = 0; i< 20; i++) for(int j = 0; j<5; j++) grades[i][j] = 100; String[][] colours = {{"Red", "Green", "Blue"}, {"Cyan", "Magenta", "Yellow"}, {"Russet", "Mauve", "Orange"}};