Professional Documents
Culture Documents
Lecture 4
Lecture 4
FOUR
1
STRING HANDLING IN
JAVA
Java implement strings as objects of type String.
It belongs to java.lang.
Once a String object is created, it is not possible to
change the characters that comprise the string.
When a modifiable string is needed, java provides two
options:
1.java.lang.StringBuffer
2.java.lang.StringBuilder
2
THE STRING
CONSTRUCTOR
1. String()- Example: String s = new String();
2. String (char chars[])
Example:
char chars[] = {‘a’, ‘b’, ’c’};
String s=new String (chars);
3. String( char chars[], int startIndex, int numChars);
Example:
char chars[] = {‘a’, ‘b’, ’c’, ‘d’, ‘e’, ‘f’};
String s = new String (chars, 2, 3);
3
THE STRING
CONSTRUCTOR
4. String (String str);
Example:
char c[] = {‘j’, ‘a’, ‘v’, ‘a’};
String s1 = new String (c);
System.out.println (s1);
4
String Length:
int length();
Example:
char st [ ] = {‘a’, ‘b’, ‘c’};
String a = new String (st);
System.out.println ( a.length());
5
STRING CONCATENATION
Java allows only + operator to be applied on string, which concatenates
of two strings.
Example:
String age = “9”;
String s = “He is “ + age + “ years old.”;
System.out.println (s);
} }
}
CHARACTER
EXTRACTION
1. charAt ():
char ch;
ch = “abc”.charAt(1); ch<-’b’
9
STRING COMPARISON
1. equals ()
boolean equals( String str)
-str is the String object being compared with the
invoking String object.
-Case sensitive.
2. equalsIgnoreCase ()
boolean equalsIgnoreCase( String str)
-str is the String object being compared with the
invoking String object.
-Not case sensitive.
10
STRING COMPARISON
Example:
String s1 = “Hello”;
String s2 = “HELLO”;
System.out.println ( s1 + “ equals “ +s2 + s1.equals(s2));
System.out.println ( s1 + “ equals “ +s2 + s1.equalsIgnoreCase(s2));
Output:
Hello equals HELLO false
Hello equals HELLO true
11
STRING COMPARISON
. StartsWith () and endsWith ()
Example:
“Football”. endsWith ( “ball”); --- returns true
“Football”. startsWith (“wood”); ----returns false
12
STRING COMPARISON
5. int compareTo (String str)
- less than 0: if invoking string is less than str
greater than 0: if invoking string is greater than str
0: if equal
- case sensitive.
13
EQUALS () VERSUS ==
equals () method compares the characters within a String
object.
The == operator compares two object references to see whether
they refer to the same object.
Example:
String s1 = “hello”;
String s2 = new String(s1);
System.out.println(s1 + “ equals “+s2 + “ ”+ s1.equals(s2));
System.out.println(s1 + “ equals “+s2 + “ ”+ (s1==s2));
Output:
hello equals hello true
14
hello equals hello false