Java String Class String is a class

Slides:



Advertisements
Similar presentations
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Advertisements

Building Java Programs
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
ArrayList, Multidimensional Arrays
From C++ to Java A whirlwind tour of Java for C++ programmers.
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.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
CPS Anagram: Using Normalizers l How can we normalize an Anaword object differently?  Call normalize explicitly on all Anaword objects  Have.
Compsci 100, Fall Data and Information How and why do we organize data? Differences between data and information? What about knowledge?
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
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.
CompSci 100E 1.1 CompSci 100E Dietolf (Dee) Ramm Robert A. Wagner
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
CSE 143 Lecture 2 ArrayList reading: 10.1 slides created by Marty Stepp
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
CPS APTs and structuring data/information l Is an element in an array, Where is an element in an array?  DIY: use a loop  Use Collections, several.
CompSci Reading from Files  import java.io.File;  Declare a file File fileOfCats = new File(”cats.txt”);  Use file – pass it as an argument to.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
CPS What's in Compsci 100? l Understanding tradeoffs: reasoning, analyzing, describing…  Algorithms  Data Structures  Programming  Design l.
CPS Anagram: Using Normalizers l How can we normalize an Anaword object differently?  Call normalize explicitly on all Anaword objects  Have.
Chapter 9 Introduction to Arrays Fundamentals of Java.
CompSci Toward understanding data structures  What can be put in a TreeSet?  What can be sorted?  Where do we find this information?  How do.
Java: Base Types All information has a type or class designation
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Lecture 5:Interfaces and Abstract Classes
CMSC 202 ArrayList Aug 9, 2007.
Java Arrays Fixed size, once created
Lecture 10 Collections Richard Gesick.
Java Arrays and ArrayLists COMP T1 #5
Computer Organization and Design Pointers, Arrays and Strings in C
Sixth Lecture ArrayList Abstract Class and Interface
Object-oriented Programming in Java
Java: Base Types All information has a type or class designation
Object-Oriented Java Programming
John Hurley Cal State LA
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Programming Language Concepts (CIS 635)
Interfaces and Inheritance
Continuing Chapter 11 Inheritance and Polymorphism
Top Ten Words that Almost Rhyme with “Peas”
String and StringBuilder
TCSS 143, Autumn 2004 Lecture Notes
Can store many of the same kind of data together
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Polymorphism.
ArrayLists.
String and StringBuilder
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Arrays versus ArrayList
CMSC 202 ArrayList Aug 9, 2007.
int [] scores = new int [10];
Can store many of the same kind of data together
Dynamic Data Structures and Generics
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
16 Strings.
int [] scores = new int [10];
Computer Science and Engineering
ArrayLists 22-Feb-19.
Can store many of the same kind of data together
String and StringBuilder
Suggested self-checks: Section 7.11 #1-11
Java Programming Language
Review: libraries and packages
Object-Oriented Java Programming
Arrays.
Presentation transcript:

Java String Class String is a class Do not need new to create String String msg = ”hello”; Can join strings (concatenate) with + String mail = ”John says ” + msg; Most common String methods: int length(); // get number of chars in it String substring(int start, int stop); // substring gets part of string int indexOf(String key); // finds loc of key char charAt(int index); // get a single char

String Methods More on useful String methods Examples. What are the values? String demo = ”How are things?”; demo.substring(8, 12) demo.indexOf(”wa”) demo.indexOf(”w a”) demo.charAt(7); Other common String methods boolean equals(String s) // equality of contents int compareTo(String s) // -1, 0, +1 : <, ==, > String substring(int start) // end of string demo.comparetTo(”how are things?”) demo.equals (”how are things?”) demo.substring(10)

Why Inheritance? Add new shapes easily without changing much code Shape s1 = new Circle(); Shape s2 = new Square(); Interface/abstract base class: interface or abstraction Function called at runtime concrete subclass All abstract functions implemented Later we'll override “is-a” view of inheritance Substitutable for, usable in all cases as-a shape mammal ScoreEntry FullHouse, LargeStraight User’s eye view: think and program with abstractions, realize different, but conforming implementations, don’t commit to something concrete until as late as possible

Example of Inheritance What is behavior of a shape? void doShape(Shape s) { System.out.println(s.area()); System.out.println(s.perimeter()); s.expand(2.0); } Shape s1 = new Circle(2); Shape s2 = new Square(4); Shape s3 = new Rectangle(2,5); doShape(s1); doShape(s2); doShape(s3);

Inheritance (language independent) First view: exploit common interfaces in programming Iterators in Java or C++ Implementation varies while interface stays the same Second view: share code, factor code into parent class Code in parent class shared by subclasses Subclasses can override inherited method Subclasses can override and call Polymorphism/late(runtime) binding (compare: static) Function actually called determined when program runs, not when program is compiled

What can an Object do (to itself)? http://java.sun.com/j2se/1.5.0/docs/api/ Look at java.lang.Object toString() Used to print (System.out.println) an object, overriding toString() can result in 'useful' information being printed, also used in String concatenation: String s = x + y; Default is basically a pointer-value equals() Determines if guts of two objects are the same, must override, e.g., for using a.indexOf(o) in ArrayList a Default is ==, pointer equality hashCode() Hashes object (guts) to value for efficient lookup

What's in the boxes? "genome" is in the boxes Objects and Values Primitive variables are boxes think memory location with value Object variables are labels that are put on boxes String s = new String("genome"); String t = new String("genome"); if (s == t) {they label the same box} if (s.equals(t)) {contents of boxes the same} s t What's in the boxes? "genome" is in the boxes

Objects, Values, Classes For primitive types: int, char, double, boolean Variables have names and are themselves boxes (metaphorically) Two int variables assigned 17 are equal with == For object types: String, Sequence, others Variables have names and are labels for boxes If no box assigned, created, then label applied to null Can assign label to existing box (via another label) Can create new box using new Object types are references or pointers or labels to storage

Java Arrays Fixed size, once created Can hold primitive types Can hold objects (references) Example: Creating an array of doubles double[] times; times = new double[30]; // or could combine w prev Example: Creating an array of DLicenses DLicense[] dls; dls = new DLicense[50]; // create array (or combine) for (int k; k < dls.length; k++) { dls[k] = new DLicense(); // create objects in dls }

Java Arrays Can also create arrays by specifying initial values Avoids need for new Avoids need to count the number of values Example: Creating an array of ints int[] counts = { 3, 12, 0, 8, 10}; Use counts.length to get size of array Example: Creating an array of Strings String[] aHotel = {”Hilton”, ”Swans”, ”Astoria”}; String[] bHotel = {”Kwik8”, ”SleepyT”, ”TuckUIn”}; String[] cHotel = {”DiveX”, ”RRXing”, ”Swampys”}; Example: Creating an array of arrays (matrix) String[][] hotelChoice = {aHotel, bHotel, cHotel};

Java ArrayList Class Flexible Arrays Create with: Grows in size as needed! Many different methods to improved array processing Create with: ArrayList list = new ArrayList(); Uses: (assume dl, sl, are DLicense objects) list.add(dl); // add to “end” (append) list.add(k, dl); // insert at position k (shifts!) list.set(k, dl); // replace at position k // retrieve from position m – note cast to DLicense sl = (DLicense) list.get(m);

Java ArrayList Class Print out with: (dl is a DLicense object and list an ArrayList of DLicense) for (int k = 0; k < list.size(); k++) { DLicense licns = (Dlicense) list.get(k); System.out.println(licns.getName() + ” ” + licns.getNum()); } Note that brackets [ ] don’t work ! ! ! Also see: remove(), indexOf(), toArray(), contains(), size(), ... Look them up in API!

For-Each Loop (new with Java 5) For Arrays (and Collections) May Use Special Loop Syntax for (Type name : expression){ body of loop } Type is the type of object returned for use in loop name is of variable that take on value for use in loop expresssion is an array or collection Example: (list is an ArrayList of Dlicense objects) for (DLicense dl : list) { System.out.println(dl.getName() + ” ” + dl.getNum()); But cannot change entries! (effectively dealing with copy)

Java ArrayList Class (Java 5) Generic forms Previous example stored items as Objects On retrieving, needed to cast back to original class Create with: ArrayList<DLicense> vect = new ArrayList<DLicense>(); Use: (assume sl, is a DLicense objects) sl = list.get(m); // get at position m: no cast needed for (DLicense cl : list) { System.out.println(”Number is ” + cl.getNum()); }