150 likes | 292 Vues
ICS3U – String. Teacher: Mr. Ho Course URL: http://computerNHSS.wikispaces.com. What is String in Java. String is a data type It is a sequence of characters E.g.1, “Computer” E.g.2, “We love Computer Science!”. How to Use String in Java.
E N D
ICS3U – String Teacher: Mr. Ho Course URL: http://computerNHSS.wikispaces.com
What is String in Java • String is a data type • It is a sequence of characters • E.g.1, “Computer” • E.g.2, “We love Computer Science!”
How to Use String in Java • First, declare a variable of String type inside the main method • In main(): String word = “Apple”;
Built-in Methods • String word = “AppLe”; • word.length(); // length of the word • word.charAt(3); // character at index 3 • word.substring(2, 4); // substring • word.toUpperCase(); // upper case • word.toLowerCase(); // lower case • word.indexOf(‘p’); // first occurrence of ‘p’ • word.indexOf(“pp”); // first occurrence of “pp” • word.lastIndexOf(‘p’); // last occurrence of ‘p’ • word.equals(“apple”); // Is “AppLe” equal “apple”? • word.equalsIgnoreCase(“apple”);
word.length() In the main() method: String word = “AppLe”; System.out.println(word.length()); Output: 5
word.charAt(3) In the main() method: String word = “AppLe”; System.out.println(word.charAt(3)); Output: L
word.substring(2, 4) In the main() method: String word = “AppLe”; System.out.println(word.substring(2,4)); Output: pL
word.toUpperCase() In the main() method: String word = “AppLe”; System.out.println(word.toUpperCase()); Output: APPLE
word.toLowerCase() In the main() method: String word = “AppLe”; System.out.println(word.toLowerCase()); Output: apple
word.indexOf(‘p’) In the main() method: String word = “AppLe”; System.out.println(word.indexOf(‘p’)); Output: 1
word.indexOf(“pp”) In the main() method: String word = “AppLe”; System.out.println(word.indexOf(“pp”)); Output: 1
word.lastIndexOf(‘p’) In the main() method: String word = “AppLe”; System.out.println(word.lastIndexOf(‘p’)); Output: 2
word.equals(“apple”) In the main() method: String word = “AppLe”; System.out.println(word.equals(“apple”)); Output: false
word.equalsIgnoreCase(“apple”) In the main() method: String word = “AppLe”; System.out.println( word.equalsIgnoreCase(“apple”)); Output: true
Classwork • Go to http://computerNHSS.wikispaces.com • Download the classwork: • JBB_pg_16.pdf • JBB_pg_17.pdf • Work on #1, 2, and 4