0% found this document useful (0 votes)
11 views

Chapter 4

The document discusses the String class in Java and its key properties and methods. Strings are immutable objects that represent a sequence of characters. Common string methods allow accessing characters by index, comparing strings, extracting substrings, and converting case. Interned strings improve efficiency by sharing a single instance for identical string values.

Uploaded by

Abrham Tegegne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Chapter 4

The document discusses the String class in Java and its key properties and methods. Strings are immutable objects that represent a sequence of characters. Common string methods allow accessing characters by index, comparing strings, extracting substrings, and converting case. Interned strings improve efficiency by sharing a single instance for identical string values.

Uploaded by

Abrham Tegegne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Object-Oriented Programming

Chapter 3: Strings
1
Introduction
An object of the String class represents a string of
characters.
The String class belongs to the java.lang package, which
does not require an import statement.
Like other classes, String has constructors and
methods.
The easiest way of creating a String object is using a string
literal:
String str1 = "I can’t be changed once created!";
The Java language provides special support for the string
concatenation operator ( + and += ), which has been
overloaded for Strings objects. (String concatenation) 2
Introduction
String concatenation is implemented through the
StringBuffer class and its append method.
Example
 String finalString = “Hello” + “World”;
String objects can also be created through constructors
Examples
String s1 = new String();
/*Create String with the value */
String s2 = new String (“ Hello World!”);
char data[] = { 'a', 'b', 'c' };
String s3 = new String( data );

3
Immutability
A Java String is read-only and once created the
contents cannot be modified. i.e. its content can never
be changed. That is String object is immutable
Example
 String s = "java";
 System.out.println(s); //output: java
 s= "abc";
 System.out.println(s); //output: abc
 s += " def";
 System.out.println(s); //output: abc def

4
Immutability…
String s = "Java";
s = "HTML";

After executing String s = "Java"; After executing s = "HTML";

s : String s : String This string object is


now unreferenced
String object for "Java" String object for "Java"

Contents cannot be changed : String

String object for "HTML"

5
Advantages Of Immutability
Immutable objects are convenient because several references
can point to the same object safely: there is no danger of
changing an object through one reference without the others
being aware of the change.
Uses less memory.
String word1 = "Java"; String word1 = “Java";
String word2 = word1; String word2 = new String(word1);

word1 word1 “Java"

“Java" word2 “Java"


word2
Less efficient:
OK wastes memory

6
Disadvantages of Immutability
Less efficient:- We need to create a new string and throw
away
the old one even for small changes.

String word = “java";


char ch = Character.toUpperCase(word.charAt (0));
word = ch + word.substring (1);

word “java"

“Java"

7
Interned Strings
Since strings are immutable and are frequently used, to
improve efficiency and save memory, the JVM uses a unique
instance for string literals with the same character sequence.
Such an instance is called interned. You can also use a String
object’s intern method to return an interned string.
For example, the following statements:
s
String s = "Welcome to Java"; : String
s2
String s1 = new String("Welcome to Java"); s3 Interned string object for
"Welcome to Java "
String s2 = s.intern();

String s3 = "Welcome to Java"; s1 : String


System.out.println("s1 == s is " + (s1 == s)); A string object for
System.out.println("s2 == s is " + (s2 == s)); "Welcome to Java "
System.out.println("s == s3 is " + (s == s3));

8
Interned Strings…
Output:
s1 == s is false
s2 == s is true
s == s3 is true

If new is not used to assign a value to a String object,


then all other Strings constructed similarly
with the same literal value will refer to the same object
in memory.

9
String Methods
int length()
Returns the number of characters in the string
Example
 int x = “Java”.length; //x = 4
 String s = “Hello, there”;
 int y = s.length(); //y = 12

char charAt(i)
Returns the char at position i.
Character positions in strings are numbered starting
from 0 – just like arrays.
Example
 ”Window".charAt (2); // ’n’

10
String Methods…
void getChars(int si, int li, Char[] ca, fi)
Used to copy the characters of a string into a character array
 si is the starting index in the string from which characters are to
be copied.
 li is the index that is one past the last character to be copied from

the string.
 ca is the character array into which the characters are to be copied
 fi is the starting index where the copied characters are placed in

the target character array. Next


Example
 String s1 = "hello there";
 char charArray[] = new char[ 5 ];
 s1.getChars( 0, 5, charArray, 0 ); // copy characters from string into charArray

11
String Methods…
int compareTo( String str )
Compares the current String object to str, and returns 0
only if the two strings contain the same sequence of
characters (case sensative).
A negative value is returned if the current String is lower
in the Unicode set than the String str.
 A positive value is returned if the current String is
higher in the Unicode set than the String str.
Example
 String word = “Dog”
 if ( word.compareTo("dog") > 0 )…

12
String Methods…
int compareToIgnoreCase (String str)
 This message is like compareTo, except that it compares
Strings without regard to capitalization.
boolean equals( Object obj )
 Compares the current String object with obj and returns true
if obj is another String containing the same sequence of
characters; false is returned otherwise.
 Example
 String Command = “Close”;
 if ( command.equals( "quit" ) ) { … }
boolean equalsIgnoreCase( String str )
 Performs a case-insensitive comparison of the current String
object with str and returns true if str is another String
containing the same sequence (ignoring case) of characters;
false is returned otherwise. 13
String Methods…
== operator
Use of the == operator only tests whether two String
object references refer to the same object (memory
space).
The == operator does not test whether the contents of
the two Strings are equal.

•Never use == to test equality of String contents.


14
String Methods…
String concat( String str )
 Concatenates the specified String to the end of the current (this)
String.
 If the length of the argument string is 0, then this String is
returned.
 Example
 “Hello”.concat(“Java”);
String toUpperCase()
 Converts the String to uppercase.
 Example
 “Java”.toUpperCase()
String toLowerCase()
 Converts the String to lowercase
 Example
 “Java”.toLowerCase() 15
String Methods…
int indexOf(int c)
Returns the index of first occurrence of the argument char.
int indexOf(int c, int fromIndex)
Finds the index of the first occurrence of the argument
character in a string, starting at the index specified in the
second argument.
int indexOf(String str)
Finds the start index of the first occurrence of the
substring argument in a String.
int indexOf(String str, int fromIndex)
Finds the start index of the first occurrence of the
substring argument in a String, starting at the index
specified in the second argument.
16
String Methods…
The String class also provides methods to search for a
character or string in backward direction.
These methods are given below.
int lastIndexOf(int ch)
int lastIndexOf(int ch, int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
String replace(char oldChar, int newchar)
used to replace all occurrences of the specified character
with given character.
String trim()
This method removes white space from the front and the
end of a String.
17
String Methods…
String substring(int startIndex)
Extracts a multi-character substring from a String starting
from startIndex to the end of the String
Example
 String source = "wombat";
 String sub = source.substring( 1); //sub = bat
String substring(int startIndex, int endIndex)
Extracts a multi-character substring from a String starting
from startIndex to endIndex(not included).
Example
String source = "wombat";
 String sub = source.substring( 1, 3 ); //sub = om

18
Converting Numbers to Strings
Three ways to convert a number into a string:
1. Using “”
String s = "" + num;
Example
S = “” + 123; //123
2. Using toStrings() method
String s = Integer.toString (i);
String s = Double.toString (d);
Example
 s = Integer.toString(123);//”123”
 s = Double.toString(3.14); //”3.14”

 Integer and Double are “wrapper” classes from java.lang that


represent numbers as objects. They also provide useful static
methods.

19
Converting Numbers to Strings…
3. Using valueOf() method
String class provides set of static overloaded valueOf
method to convert primitives and object into strings.
Creates the String representation of the argument.
 static String valueOf(Object obj)
 static String valueOf(char[] character)
 static String valueOf(boolean b)
 static String valueOf(char c)
 static String valueOf(int i)
 static String valueOf(long l)
 static String valueOf(float f)
 static String valueOf(double d)

Example
 s = String.valueOf(123);//”123” 20
Converting Strings to Numbers
To convert a string value to a number (for example, to
convert the String value in a text field to an int), use
these methods.
Assume the following declarations:
String s; int i; long l; float f; double d;

If s is null or not a valid representation of a number of that type,


these methods will throw (generate) a NumberFormatException.
21
StringBuilder and StringBuffer
Strings are immutable (can't be changed), so manipulating
strings often causes many temporary string objects to be
created, which can be quite inefficient.
StringBuilder (or StringBuffer) are better choices in these
cases.
Their toString() method can be used to get a String value.
It isn't necessary to create them with a specific size, it will
expand as necessary.
StringBuilder (was added in Java 5) is basically identical to the
older StringBuffer, but is slightly faster because it isn't
synchronized (if multiple threads are accessing it at the same
time, there could be trouble.).
StringBuilder and StringBuffer are defined inside java.lang.
22
StringBuilder examples
/**
Creates a few StringBuilder objects and uses the append and
insert methods to add text to them.
We use the \n character for line breaks.
*/
public class Example{
public static void main(String[] args) {

//Create the StringBuilder


StringBuilder builder = new StringBuilder("Line 1\n");

//Append text to the end of the buffer


builder.append("Line 3\n");

//Now we want to add text in between line 1 and line 3


String lineToInsert = "Line 2\n";
int index = builder.indexOf("Line 3");
builder.insert(index, lineToInsert);

System.out.println(builder.toString());

}
23
}
StringBuffer Example

public class AppendInsert{


public static void main(String[] args) {
System.out.println("StringBuffer insert and append example!");
StringBuffer sb = new StringBuffer(0);
//First position
System.out.println(sb.insert(0, "vinod"));
int len = sb.length();
//last position
System.out.println(sb.insert(len, "Deepak"));
//Six position
System.out.println(sb.insert(6, "Raj"));
//Always last
System.out.println(sb.append("Mohit"));
}
}

24

You might also like