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.

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

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 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.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Chapter 10.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
Java Syntax Primitive data types Operators Control statements.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Fundamental Programming Structures in Java: Strings.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
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.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
1 Chapter 4: Arrays and strings Taufik Djatna
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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.
Chapter 8: Arrays.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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
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 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.
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.
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:
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
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.
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.
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
String & Exception. Lesson plan Class & Object String Exercise for midterm.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
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
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Array, Strings and Vectors
String class.
Selenium WebDriver Web Test Tool Training
String Handling in JAVA
Java Review: Reference Types
Primitive Types Vs. Reference Types, Strings, Enumerations
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.
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:

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

 Although we haven't yet discussed classes and object, we will discuss the String class.  String objects are handled specially by the compiler.  String is the only class which has "implicit" instantiation.  The String class is defined in the java.lang package.  Strings are immutable. The value of a String object can never be changed.  For mutable Strings, use the StringBuffer class. 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

 StringBuffer objects are similar to String objects  Strings are immutable  StringBuffers are mutable  The StringBuffer class defines methods for modifying the String value  insert()  append()  setLength()  To clear a StringBuffer, set it's length to 0 The StringBuffer Class StringBuffer nameBuffer = new StringBuffer("Joe"); [...] nameBuffer.setLength(0); // clear StringBuffer

StringBuffer Example StringBuffer sql = new StringBuffer(); sql.setLength(0); sql.append("Select * from Employee"); sql.append(" where Employee_ID = " + employeeId); sql.append(" and Employee_name = '" + employeeName + "'");

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

Review  Is String a fundamental data type in Java?  How is the String class treated specially?  Name some commonly used methods of the String class and describe their function.  What is a StringBuffer?  What is an array?  What are the steps needed to create and use an array?  How are arrays initialized?  How does bounds checking work in Java?  What are the parameters to the method called "main"?