String Pemrograman Berbasis Obyek Oleh Tita Karlita.

Slides:



Advertisements
Similar presentations
1 Arrays, Strings and Collections [2] Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering.
Advertisements

Java
1 StringBuffer & StringTokenizer Classes Chapter 5 - Other String Classes.
Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the.
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.
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.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Lecture 14 March 23, Exam Results Class Average was 69.4 –Median was 72.5 (which means there were some very low grades) Questions 31, 32, and 33.
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Chapter 7: Characters, Strings, and the StringBuilder.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
String Handling StringBuffer class character class StringTokenizer class.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
CSI 3125, Preliminaries, page 1 String. CSI 3125, Preliminaries, page 2 String Class Java provides the String class to create and manipulate strings.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
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 String Manipulation
The String class is defined in the java.lang package
String and StringBuffer classes
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
EKT 472: Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
String and String Buffers
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
String class in java Visit for more Learning Resources string.
Modern Programming Tools And Techniques-I Lecture 11: String Handling
String and StringBuilder
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
String and StringBuilder
String and StringBuilder
Java – String Handling.
Lecture 07 String Jaeki Song.
String and StringBuilder
Object Oriented Programming
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:

String Pemrograman Berbasis Obyek Oleh Tita Karlita

The String Class  Common string constructors: String s1 = new String(“immutable”); String s1 = “immutable”;  Class String berisi string yang tetap (immutable string).  Sekali intance String dibuat maka isinya tidak bisa diubah.

 Sebagaimana object java yang lain, object String bisa dibuat dengan menggunakan operator new (menggunakan constructor).  Kelas String memiliki 13 constructors yang memungkinkan kita membuat object String dan menginisialisasi nilainya dengan menggunakan berbagai macam sumber data yang berbeda.  Contoh: char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String helloString = new String(helloArray); System.out.println(helloString); The last line of this code snippet displays hello.

 Java mempunyai media penyimpanan literal string yang yang disebut “pool”.  Jika suatu literal string sudah ada di pool, Java “tidak akan membuat copy lagi”.

Identical literals 1. String s1 = “Compare me”; 2. String s2 = “Compare me”; 3. if (s1.equals(s2)) { 4. // whatever 5. } 1. String s1 = “Compare me”; 2. String s2 = “Compare me”; 3. if (s1 == s2)) { 4. // whatever 5. }  Kedua potongan program diatas OK  Contoh pertama membandingkan contentnya.  Contoh kedua membandingkan referencesnya.

Explicitly calling the String constructor String s2 = new String(“Constructed”);  Pada saat kompile  “Constructed” disimpan di pool tersendiri.  Pada saat runtime  statement new String() dieksekusi, “Constructed” akan dibuatkan lagi di program space.  Bila di pool sudah ada “Constructed”, akan tetap dibuatkan program space.  Supaya “Constructed” benar-benar disimpan di pool maka gunakan method intern().

equals() dan == untuk String  Method equals() membandingkan content-nya  == membandingkan alamatnya.

Variabel java1 dieksekusi pada saat runtime

String Length  Methods used to obtain information about an object are known as accessor methods.  One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.  After the following two lines of code have been executed, len equals 17: String palindrome = "Dot saw I was Tod"; int len = palindrome.length();

Here is a short and inefficient program to reverse a palindrome string. It invokes the String method charAt(i), which returns the i th character in the string, counting from 0. public class StringDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len]; // put original string in an array of chars for (int i = 0; i < len; i++) { tempCharArray[i] = palindrome.charAt(i); } // reverse array of chars for (int j = 0; j < len; j++) { charArray[j] = tempCharArray[len j]; } String reversePalindrome = new String(charArray); System.out.println(reversePalindrome); } palindrome.getChars(0, len, tempCharArray, 0); // put original string in an array of chars for (int i = 0; i < len; i++) { tempCharArray[i] = palindrome.charAt(i); }

Concatenating Strings  The String class includes a method for concatenating two strings: string1.concat(string2);  This returns a new string that is string1 with string2 added to it at the end.  You can also use the concat() method with string literals, as in: "My name is ".concat(“Ella");  Strings are more commonly concatenated with the + operator, as in "Hello," + " world" + "!"  which results in "Hello, world!"  The + operator is widely used in print statements.  For example: String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod");  which prints Dot saw I was Tod

 Such a concatenation can be a mixture of any objects.  For each object that is not a String, its toString() method is called to convert it to a String.

String methods  char charAt(int index): Returns the indexed character of a string, where the index of the initial character is 0.  String concat(String addThis): Returns a new string consisting of the old string followed by addThis.  int compareTo(String otherString): Performs a lexical comparison; returns an int that is less than 0 if the current string is less than otherString, equal to 0 if the strings are identical, and greater than 0 if the current string is greater than otherString.  boolean endsWith(String suffix): Returns true if the current string ends with suffix; otherwise returns false.

String methods  boolean equals(Object ob): Returns true if ob instanceof String and the string encapsulated by ob matches the string encapsulated by the executing object.  boolean equalsIgnoreCase(String s): Creates a new string with the same value as the executing object, but in lower case.  int indexOf(int ch): Returns the index within the current string of the first occurrence of ch. Alternative forms return the index of a string and begin searching from a specified offset.  int lastIndexOf(int ch): Returns the index within the current string of the last occurrence of ch. Alternative forms return the index of a string and end searching at a specified offset from the end of the string.

 int length(): Returns the number of characters in the current string.  String replace(char oldChar, char newChar): Returns a new string, generated by replacing every occurrence of oldChar with newChar.  boolean startsWith(String prefix): Returns true if the current string begins with prefix; otherwise returns false. Alternate forms begin searching from a specified offset.  String substring(int startIndex): Returns the substring, beginning at startIndex of the current string and extending to the end of the current string. An alternate form specifies starting and ending offsets.  String toLowerCase(): Creates a new string with the same value as the executing object, but in lower case.

 String toString(): Returns the executing object.  String toUpperCase(): Converts the executing object to uppercase and returns a new string.  String trim(): Returns the string that results from removing whitespace characters from the beginning and ending of the current string.

Trimming and replacing 1. String s = “ = 20”; 2. s = s.trim(); // “5 + 4 = 20” 3. s = s.replace(‘+’, ‘x’); // “5 x 4 = 20”

The StringBuffer Class  represents a string that can be dynamically modified.  Constructors:  StringBuffer() : Constructs an empty string buffer  StringBuffer(int capacity) : Constructs an empty string buffer with the specified initial capacity  StringBuffer(String initialString) : Constructs a string buffer that initially contains the specified string

StringBuffer methods  StringBuffer append(String str): Appends str to the current string buffer. Alternative forms support appending primitives and character arrays; these are converted to strings before appending.  StringBuffer append(Object obj): Calls toString() on obj and appends the result to the current string buffer.  StringBuffer insert(int offset, String str): Inserts str into the current string buffer at position offset. There are numerous alternative forms.  StringBuffer reverse(): Reverses the characters of the current string buffer.  StringBuffer setCharAt(int offset, char newChar): Replaces the character at position offset with newChar.  StringBuffer setLength(int newLength): Sets the length of the string buffer to newLength. If newLength is less than the current length, the string is truncated. If newLength is greater than the current length, the string is padded with null characters.

Modifying a string buffer 1. StringBuffer sbuf = new StringBuffer(“12345”); 2. sbuf.reverse(); // “54321” 3. sbuf.insert(3, “aaa”); // “543aaa21” 4. sbuf.append(“zzz”); // “543aaa21zzz”

String Concatenation the Easy Way  concat() method of the String class  append() method of the StringBuffer class  + operator.  Example: String Concatenation: a + b + c Java compiler treats as: new StringBuffer().append(a).append(b).append(c).toString();