Chapter 4
Chapter 4
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";
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);
6
Disadvantages of Immutability
Less efficient:- We need to create a new string and throw
away
the old one even for small changes.
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();
8
Interned Strings…
Output:
s1 == s is false
s2 == s is true
s == s3 is true
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
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.
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”
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;
System.out.println(builder.toString());
}
23
}
StringBuffer Example
24