100 likes | 226 Views
STRINGS. Chapter 13. String class. A String is a Class – not a primitive Therefore, a String is a ‘doughnut’ A String object has data A String object has methods. constructors. A constructor is a method that is executed when an object is created The String class has multiple constructors
E N D
STRINGS Chapter 13
String class • A String is a Class – not a primitive • Therefore, a String is a ‘doughnut’ • A String object has data • A String object has methods
constructors • A constructor is a method that is executed when an object is created • The String class has multiple constructors • String s1; • String s2 = new String(); • String s3 = new String(“Buffalo”); • String s4 = new String(s3); • String s5 = “Bills”; • String s6 = s3 + “ “ + s5 + “ are great”;
String methods • Since a String is a class, a String object has methods • To declare a String: • String s1 = “Buffalo”; • To run a String method, you key the String object name, a . (period), and then the method name • s1.charAt(3)
length() • The length() method returns an int that contains the number of characters in the String. • A String is not an array of characters terminated by a null (that is C) • String s1 = “Buffalo”; • int x = s1.length(); // x is 7 • String s2 = “Hi Mom and Dad!”; • int x = s2.length(); // x is 15
charAt(int) • charAt(int x) returns the character that is in the xth position of the String. • Note: the first character of a String is in position 0 (not 1) • String s1 = “Buffalo”) • char ch = s1.charAt(5); // ch is an l • char ch = s1.charAt(0); // ch is an B • char ch = s1.charAt(9); // error
equals(String) • The equals method returns a true or false • String s1 = “Buffalo”; • String s2 = “Bills”; • if(s1.equals(s2)) // returns false • If(s1.equals(“Buffalo”) // returns true • If(s1 == s1) will probably return false • You cannot use == to compare Strings. • == compares the references to 2 Strings
toLowerCase() toUpperCase() • toLowerCase() returns a copy of the String with all lower case • toUpperCase() returns a copy of the String with all upper case • String s1, s2, s3 = “Buffalo”; • s1 = s3.toLowerCase(s3); // buffalo • s2 = s3.toUpperCase(s3); // BUFFALO
substring() • substring(int x, int y) • Returns a substring from position x to one character before position y • substring(int x) • Returns a substring from position x to the end of the String • String s1, s2 = “Buffalo”; • s1 = s2.substring(2,5); // returns ffa • s1 = s2.substring(4); // returns alo
parseInt(String) • parseInt() is a method in the Integer class • parseInt() converts a String into an int • Int x; • String s1 = “123” • X = Integer.parseInt(“2”); // x is 2 • X = Integer.parseInt(s1); // x is 123 • X = Integer.parseInt(“ab”); // error