Sei sulla pagina 1di 16

Strings in JAVA

String is a sequence of characters.


Java implements strings as objects of type
String.
It belongs to java.lang package

We can declare a String variable and directly store a


String literal using assignment operator.
String str = "Hello";
We can create String object using new operator with
some data.
String s1 = new String ("Java");
We can create a String by using character array also
and by passing array name to it, as:
char arr[] = { 'p','r','o',g,r,a,m};
String s2 = new String (arr);
We can create a String by passing array name and
specifying which characters we need:
String s3 = new String (str, 2, 3);
Here starting from 2nd character a total of 3
characters are copied into String s3.

STRING CLASS
String is a class in Java library.
It contains few predefined methods, which can be used via
creating objects of String class.
String s1 = "Hello world!";
OR
String s1 = new String(Hello World);
length() method example:
public class StringDemo {
public static void main(String args[]) {
String s1= "Dot saw I was Tod";
int len = s1.length();
System.out.println( "String Length is : " + len );
}
}

Output:

String Length is : 17

Various String Functions


String Length:
int length();
Example:
char st [ ] = {a, b, c};
String a = new String (st);
System.out.println ( a.length());

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
hello equals hello false

STRING CLASS equals method

public class Test {


Values of Str1 & Str2 ar
public static void main(String args[]) {
Values of Str1 & Str3 ar
String Str1 = new String("HelloWorld"); Objects Str1 & Str2 in h
String Str2 = Str1;
same
String Str3 = new String("Hello World");
System.out.println(Str1.indexOf("e"));
System.out.println(Str1.substring(5, 8));
System.out.println(Str1.length());
boolean retVal;
if(Str1.equals(Str2))
System.out.println("Values of Str1 & Str2 are same");
if(Str1.equals(Str3))
System.out.println("Values of Str1 & Str3 are same");
if(Str1==Str2)
System.out.println("Objects Str1 & Str2 in heap are same");
if(Str1==Str3)
System.out.println("Objects Str1 & Str3 in heap are same");
}

String Comparisons
compareTo(Object object)
String s1 = new String("Welcome);
String s2 = "welcome";
if (s1.compareTo(s2) > 0) {
// s1 is greater than s2
}
else if (s1.compareTo(s2) == 0) {
// s1 and s2 have the same contents
}
else
// s1 is less than s2
8

Program 3: Write a program using some important


methods of String class.
// program using String class methods
class StrOps
{ public static void main(String args [])
{ String str1 = "When it comes to Web programming,
Java is #1.";
String str2 = new String (str1);
String str3 = "Java strings are powerful.";
int result, idx; char ch;
System.out.println ("Length of str1: " + str1.length
());
// display str1, one char at a time.
for(int i=0; i < str1.length(); i++)
System.out.print (str1.charAt (i));
System.out.println ();
if (str1.equals (str2) )
System.out.println ("str1 equals str2");
}

else
System.out.println ("str1 does not equal str2");
if (str1.equals (str3) )
System.out.println ("str1 equals str3");
else
System.out.println ("str1 does not equal str3");
result = str1.compareTo (str3);
if(result == 0)
System.out.println ("str1 and str3 are equal");
else if(result < 0)
System.out.println ("str1 is less than str3");
else
System.out.println ("str1 is greater than str3");
str2 = "One Two Three One"; // assign a new string to str2
idx = str2.indexOf ("One");
System.out.println ("Index of first occurrence of One: " +
idx);
idx = str2.lastIndexOf("One");
System.out.println ("Index of last occurrence of One: " +
idx);

String Concatenation
String s3 = s1.concat(s2);

String s3 = s1 + s2;
s1 + s2 + s3 + s4 + s5 same as
(((s1.concat(s2)).concat(s3)).concat(s4)).co
ncat(s5);

Examples
"Welcome".toLowerCase() returns a new string,
welcome.
"Welcome".toUpperCase() returns a new string,
WELCOME.
" Welcome ".trim() returns a new string, Welcome.
"Welcome".replace('e', 'A') returns a new string,
WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new
string, WABlcome.
"Welcome".replaceall("e", "AB") returns a new string,
WABlcomAB.
"Welcome".replace("el", "AB") returns a new string,
WABcome.

Converting, Replacing, and Splitting


Strings
java.lang.String
+toLowerCase(): String

Returns a new string with all characters converted to lowercase.

+toUpperCase(): String

Returns a new string with all characters converted to uppercase.

+trim(): String

Returns a new string with blank characters trimmed on both sides.

+replace(oldChar: char,
newChar: char): String

Returns a new string that replaces all matching character in this


string with the new character.

+replaceFirst(oldString: String, Returns a new string that replaces the first matching substring in
newString: String): String
this string with the new substring.
+replaceAll(oldString: String, Returns a new string that replace all matching substrings in this
newString: String): String
string with the new substring.
+split(delimiter: String):
Returns an array of strings consisting of the substrings split by the
String[]
delimiter.

String Comparison
StartsWith () and endsWith ()
Example:
Football. endsWith ( ball);
Football. startsWith (wood);

--- returns true


----returns false

String Comparisons
java.lang.String
+equals(s1: String): boolean

Returns true if this string is equal to string s1.

+equalsIgnoreCase(s1: String):
boolean

Returns true if this string is equal to string s1 caseinsensitive.

+compareTo(s1: String): int

Returns an integer greater than 0, equal to 0, or less than 0


to indicate whether this string is greater than, equal to, or
less than s1.

+compareToIgnoreCase(s1: String):
int

Same as compareTo except that the comparison is caseinsensitive.

+regionMatches(toffset: int, s1: String, Returns true if the specified subregion of this string exactly
offset: int, len: int): boolean
matches the specified subregion in string s1.
+regionMatches(ignoreCase: boolean, Same as the preceding method except that you can specify
toffset: int, s1: String, offset: int,
whether the match is case-sensitive.
len: int): boolean
+startsWith(prefix: String): boolean

Returns true if this string starts with the specified prefix.

+endsWith(suffix: String): boolean

Returns true if this string ends with the specified suffix.

String Length, Characters,


and Combining Strings
java.lang.String
+length(): int

Returns the number of characters in this string.

+charAt(index: int): char

Returns the character at the specified index from this string.

+concat(s1: String): String

Returns a new string that concatenate this string with string s1.
string.

Potrebbero piacerti anche