2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

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.
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
Strings in Java 1. strings in java are handled by two classes String &
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.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
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.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Programming 2 CS112- Lab 2 Java
String class  Construct a string  String str = new String(“welcome”);  Char[] charr = {‘G’, ‘o’, ‘o’, ‘d’};  String mes = new String(charr);  A full.
Chapter 7: The String class We’ll go through some of this quickly!
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.
1 Strings and String Operations Overview l Creating String Objects l Substring methods l The Concatenation Operator l Strings are Immutable l Other Methods.
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
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,
Fundamental Programming Structures in Java: Strings.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
28-Jun-15 String and StringBuilder Part I: String.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Why Java? Free! Lots of support and use – Google, Android, Oracle – Java has been around for over 20 years And is only getting more popular! Platform Independent.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
From C++ to Java A whirlwind tour of Java for C++ programmers.
String & Composition. Agenda This keyword. String class. String operations. Composition.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 8 Strings 1.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Working with string In java Four classes are provided to work with String:1) String 2)String Buffer 3)String Tokenizer 4)String Builder Note: An object.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
CHAPTER 8 File Input Output Part 1: String. The String Class  Constructing a String: String message = "Welcome to Java“; String message = new String("Welcome.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
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.
17-Feb-16 String and StringBuilder Part I: String.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings Chapter.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
(Dreaded) Quiz 2 Next Monday.
String and StringBuffer classes
Strings.
EKT 472: Object Oriented Programming
Programming in Java Text Books :
String Handling in JAVA
String and StringBuilder
Chapter 7: Strings and Characters
String and StringBuilder
Chapter 9 Strings and Text I/O
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Introducing Arrays Array is a data structure that represents a collection of the same types of data.
String and StringBuilder
Object Oriented Programming in java
Chapter 6 Arrays.
String and StringBuilder
Chapter 6 Arrays.
String methods 26-Apr-19.
Strings in Java.
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Presentation transcript:

2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".

3 Declaring and Creating Arrays datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10];  The new keyword is a Java operator that creates the object.  new calls a constructor, which initializes the new object.  Everything in java is class-based. So we need to make objects (instances) for anything that isn’t a primitive type.  ints, doubles, chars are primitive types  Arrays aren’t

4 Declaring, creating, initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;

Can do: int[] anArr = {1, 9, 4, 3}; int[] anArr = new int[4]; anArr[0] = 1; anArr[1] = 9; anArr[2] = 4; anArr[3] = 3; Can’t do: int[] anArr = new int[4]; anArr = {1, 9, 4, 3}; //can’t initialize // after initializing anArr[4] = 5; //Arrays are FIXED LENGTH!

Structural Repetition using Loops Often used when executing code for each element in a collection of data double[] data = {3.2, 4.1, 2.1}; double sum = 0; for (double echidnas : data) { sum += echidnas; } System.out.println(sum);

 What if we want to add values to the end of our array? public static int[] addingarrays(int[] arr1, int[] arr2){ int x = arr1.length; int y = arr2.length; int[] newarr = new int[x+y]; for (int ind=0;ind<arr1.length;ind++) { newarr[ind]= arr1[ind]; System.out.println(newarr[ind]); } for (int ind=0;ind<arr2.length; ind++){ newarr[x+ind] = arr2[ind]; System.out.println(newarr[x+ind]); } System.out.println(newarr); //will this work? return newarr; }

java.util.Arrays import java.util.Arrays; public class ArrayMethods { public static void print(int[] newarr) { System.out.println(Arrays.toString(newarr)); } //... }  Contains useful methods for dealing with Arrays, including:  Sort  Arrays.sort(values);  binarySearch  int index = Arrays.binarySearch(values,3);  Equals  Arrays.equals(values,array2) // sees if values inside of array are equal  Fill  int[] array = new int[5];  Arrays.fill(array,0);  toString No sum!! You have to write your own.

To Try: 1.Write a method that takes as input parameters two arrays of ints, each array being the same length (obtained by arr.length). The method creates a new array, twice as long, with the two arrays joined so that: the first value is arr[0], the second value is arr2[0], the third value is arr[1], the fourth is arr2[1], etc. It returns that new array. 1.Write a method that takes as input an array of integers, in order, and a number. The method should create a new array, with the number inserted into the correct (ordered) location. It should return this array.

public static void main (String[] args) { int [] k = {3,2,5,7}; int[] m = {8,6,4,9}; int[] x = f1(k,m); System.out.println(Arrays.toString(x)); int n[] = {3,7,12,18,27,47,52}; int[] y = f2(n,42); System.out.println(Arrays.toString(y)); } public static int[] f1(int[] arr1, int[] arr2){ int x = arr1.length; int[] newarr = new int[x*2]; for (int i=0;i<arr1.length;i++) { newarr[i*2]= arr1[i]; newarr[i*2+1] = arr2[i]; } return newarr; } public static int[] f2(int[] arr1, int x){ int y = arr1.length; int[] newarr = new int[y+1]; int a = 0; for (int i=0;i<arr1.length;i++) { if ((arr1[i] > x) && (a==0)) { newarr[i] = x; a = 1; } newarr[i+a]= arr1[i]; } return newarr; }

Recursion: Looping public static int r1(int x) { if (x == 0) { return(x); } else { return(x + r1(x-1)); } System.out.println(r1(5)); Remember – Every function call can be replaced with what the function returns If what is returned includes another function call, we must calculate what that function call returns before we know what is returned from the original function call All initialization must happen OUTSIDE the function (method) The only thing that happens only once in a recursive function is the stopping condition

Look at what is returned from each function call What is our stopping condition? public static int r4(int x, int y) { if (x == 1) { return(0); } else if (y%x == 0) { return(1 + r4(x-1,y)); } else { return(0+ r4(x-1,y)); } System.out.println(r4(11,12));

public static int r3(int x, int[] y, int z) { if (z == y.length) { return(0); } else if (y[z] == x) { return(1 + r3(x,y,z+1)); } else { return(r3(x,y,z+1)); } int[] vb = {1,0,1,1,0,0,1,0,1}; System.out.println(r3(1,vb,0));

Strings A type, but extended A class that encompasses a character array and provides many useful behaviors Chapter 9 (for the book people) Strings are IMMUTABLE

15 String Accessors message = "Welcome"; message.length() (gives us what?)

16 Retrieving Characters in a String Cannot use message[0] (strings are immutable) Use message.charAt(index) Index starts from 0

17 String Comparisons String s1 = new String("Welcome“); String s2 = "Welcome"; if (s1 == s2) { // whaddaya think? } if (s1.equals(s2)){ // do s1 and s2 have the same contents? }

18 String Comparisons, cont. compareTo(Object object) String s1 = new String("Welcome“); String s2 = "hello"; if (s1.compareTo(s2) > 0) { // is s1 greater than s2? } else if (s1.compareTo(s2) == 0) { // do s1 and s2 have the same contents? } else { // s1 is lexicographically less than s2 }

Strings are Immutable! Immutable means we can’t change them. Can’t do: String str = “hello”; str[3] = ‘b’; So then why does this work? String str = "Hello"; System.out.println(str); //Prints Hello str = "Help!"; System.out.println(str); //Prints Help!

Why can I do this? (Or, isn’t this mutating the string?) String str = "Mississippi"; System.out.println(str); //Prints Mississippi str = str.replace("i", "!"); System.out.println(str); //Prints M!ss!ss!pp!

String methods: charAt(int index) – gets the character at the index within the string and returns the char indexOf(char c)- sees if a character is within a string and returns an int representing the index indexOf(char c, int fromindex) - sees if a character is within a string from fromindex onwards length() – returns number of characters in a string (note that for strings this is a method. What is it for arrays?) substring(int beginindex) – extracts and returns a substring from a string, starting at beginindex and going to the end of the string substring(int beginindex, int endindex) – extracts and returns a substring from beginindex to endindex toLowerCase() – returns a string that is the lower case version of the string toUpperCase() – returns a string that is the upper case version of the string trim() - removes white space (space char) from both ends of a string and returns that string toCharArray() – converts string to character array and returns that array equalsIgnoreCase(String otherstring) – compares string with otherstring and returns Boolean value (true if equals, false if doesn’t) compareToIgnoreCase(String otherstring) – compares string with otherstring, and returns int (>0 if string is “greater”, 0 if equal, and <0 if “less than”.

toString() method Printing objects: – If you print an object that doesn’t have a toString() method, you print out the hash representation of the object Not what we want. – All java built-in objects have a toString method implemented. E.g., double[] x = {3.2, 7.1, 8.83, 2.5};//Color is a built-in java class -RGB System.out.println(Arrays.toString(v)); Will print out: [3.2, 7.1, 8.83, 2.5] (this is the string that the toString method explicitly created for Arrays and returned.)

toString() (Better Example) Classes should all have there own toString method written So if we create an object of the class, we can print out the object. Example: Java has a built-in class for Color objects. Every color object has 3 fields: the amount of red, the amount of green, and the amount of blue. To make an object of type color: Color x = new Color( 255, 0, 0 ); The color class has a built in toString method (all Java classes do) So we can now print out color objects using System.out.println(x) We’ll get: java.awt.Color[r=255,g=0,b=0] Also happens with concatenation, e.g.,: Color x = new Color( 255, 0, 0 ); String str = “This is color: “; str += x; toString() is a method that you should write when you create a class definition. will automatically be used as above.

Try Write a function that takes as an input parameter a string, and prints out every value in the string backwards. So, for instance, if the input string is “yranib”, the function should print out: b i n a r y