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

String Handling

Java String Class is immutable and exists in the java.lang package. Strings can be created in various ways and methods like length(), equals(), compareTo() are used to work with Strings. The document provides details about 10 common String methods like indexOf(), substring() etc.

Uploaded by

Divya Rajendran
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

String Handling

Java String Class is immutable and exists in the java.lang package. Strings can be created in various ways and methods like length(), equals(), compareTo() are used to work with Strings. The document provides details about 10 common String methods like indexOf(), substring() etc.

Uploaded by

Divya Rajendran
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Strings in java

Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot
be changed on the same reference. The String class exist in the java.lang package.

The java.lang.String class differs from other classes

 String objects can be used with the += and +operators for concatenation(ie. to combine
the strings).
 A String object can be created in many ways .

Given below are some of the different ways of creating String objects

String str1="Car Insurance" ;


String str2 = “My name ”+“is Bob”;
String str3 = “Bob”;
String str4 = “My name is” + str3;

The String object can also be created using the new operator as
String str5 = new String(“My name is bob”);

String objects can also be created from an array of characters.

Example :

char[] characters = {'S', 'T', 'U', 'V'};

//String object created from a char array


String charStr = new String(characters);
System.out.println("charStr : "+charStr);

Output
charStr : STUV
A simple way to convert any primitive value to its string representation is by concatenating it with
the empty string (“”), using the string concatenation operator (+).

Eg. 2+””, ‘a’+””, “”+2.36, 2+””+2+2 etc. become Strings.

Example

int i=10;
char c='a';
String str="";
STRINGS [CELINE BIJU – SISHYA] Page 1
String str1=i+str;
System.out.println(str1);
System.out.println(i+i);
System.out.println(i+str+i);
System.out.println(i+i+str);
System.out.println(i+i+""+i+i);

Output
10
20
1010
20
201010

Methods of Java String Class:

1. Finding the length of the string - length()


This method can be used to find the length of the string. It will return an integer.

Example :
String str = "Car insurance";
System.out.println(str.length());

Output is 13

Note : length is used to check the length of an array and length() is used to check the length of a
String object.

2. Comparing strings - equals()


The equals() method is used to compare two strings.
This function will return a boolean value i.e either a true or a false.
Example :
String str = "car finance";
if ( str.equals("car loan") )
{
System.out.println("Strings are equal");
}
else
{
System.out.println("Strings are not equal");
}
Output : Strings are not equal

STRINGS [CELINE BIJU – SISHYA] Page 2


Note: Cannot use the relational operator to check for equality between String objects .
Eg. Str1 = = str2 (cannot be used)

3. Comparing strings by ignoring case - equalsIgnoreCase()


This method is used to compare two strings by ignoring the case.
This function will return a boolean value either true or false.

Example:
String str = "insurance";
if ( str.equalsIgnoreCase("INSURANCE") )
{
System.out.println("insurance strings are equal");
}
else
{
System.out.println("insurance Strings are not equal");
}
Output : insurance strings are equal

4. Finding which string is greater - compareTo()


This method compares two strings lexicographically to find whether the first string object is
alphabetically greater ,lesser or equal to the second string object( ascii values of the alphabets are
compared).

This function will return an integer. It will return a positive value if the first string is greater than
the second string. It will return a negative value if the first string is less than the second string. It
will return 0 if both the strings are equal.
Example :
//Ascii value –‘ A’ to ‘Z’ 65 to 90
// Ascii value –‘ a’ to ‘z’ 97 to 122

String str1 = "Strings are immutable";


String str2 = "Strings are immutable";
String str3 = "Integers are mutable";

//Ascii value of ‘S’ is 84 and ‘I’ is 74

int result = str1.compareTo( str2 );


System.out.println(result);

result = str2.compareTo( str3 );

STRINGS [CELINE BIJU – SISHYA] Page 3


System.out.println(result);

result = str3.compareTo( str1 );


System.out.println(result);

Output :

0
10
-10

5. Finding which string is greater while ignoring the case - compareToIgnoreCase()

This method works like the compareTo() function but compares two strings lexicographically,
ignoring case differences.

This function after ignoring the case of the letter will return an integer . It will return a positive
value if the first string is greater than the second string. It will return a negative value if the first
string is less than the second string. It will return 0 if both the strings are equal.

Example:
String str1 = "Strings are immutable";
String str2 = "strings are immutable";
String str3 = "Integers are not immutable";
//Ascii value of ‘S’ is 84 ‘I’ is 74 ‘i’ is 106 and ‘s’ is 116

int result = str1.compareToIgnoreCase( str2 );


System.out.println(result);

result = str2.compareToIgnoreCase( str3 );


System.out.println(result);

Output :
0
10
Note : The return value ignores the case difference. Hence ‘s’ compared with ‘I’ returns 10 and not
42(116 -74)

STRINGS [CELINE BIJU – SISHYA] Page 4


The compareToIgnoreCase() method is same as the CompareTo() method except that it ignores
case while comparing alphabets.
6. Finding whether the suffix of the string is the same as the suffix passed as the parameter-
endsWith()

This function will compare the character sequence of the suffix of the String object with the
character sequence of the suffix passed as a parameter.

This method will return a boolean value i.e either true or false depending on whether the suffix
passed as a parameter is the same as the suffix of the string .

Note : the result will be true if the parameter is an empty string or is equal to the String object.

Example:
String Str = new String("This is really not immutable!!");
boolean retVal;

retVal = Str.endsWith("immutable!!");
System.out.println("Returned Value = " + retVal );

retVal = Str.endsWith("immu");
System.out.println("Returned Value = " + retVal );

retVal = Str.endsWith("");
System.out.println("Returned Value = " + retVal );

retVal = Str.endsWith("This is really not immutable!!");


System.out.println("Returned Value = " + retVal );

Output
Returned Value = true
Returned Value = false
Returned Value = true
Returned Value = true

7. Finding whether the prefix of the string is the same as the prefix passed as parameter -
startsWith() .

STRINGS [CELINE BIJU – SISHYA] Page 5


This function will compare the character sequence of the prefix of the String object with the
character sequence of the prefix passed as a parameter .

This method will return a boolean value i.e. either true or false depending on whether the prefix
passed as a parameter is the same as the prefix of the string .

Note : the result will be true if the parameter is equal to the String object.

Example:
String Str = new String("This is really not immutable!!");
boolean retVal;

retVal = Str.startsWith("This");
System.out.println("Returned Value = " + retVal );

retVal = Str.startsWith("immutable!!");
System.out.println("Returned Value = " + retVal );

retVal =Str.startsWith("This is really not immutable!!");


System.out.println("Returned Value = " + retVal );

Output
Returned Value = true
Returned Value = false
Returned Value = true

8. Finding the index Position of a String/character in another String object- from the first index/
the specified index - indexOf()

This function either takes single or two parameters and will return an integer.
The indexOf() method is used to find the index of a string or a character in another string.
This function will return the index position if the string or the character looked for in another
String object exists . If it does not exist then this method will return -1.
Example
String Str = new String("Hello Hello Hello");
String Str1 = new String("Hello");
String Str2 = new String("Sello");
//will check for occurrence of 'o' from index 0
System.out.println(Str.indexOf('o'));

STRINGS [CELINE BIJU – SISHYA] Page 6


//will check for occurrence of 6th character i.e ‘H’ from index 0
System.out.println(Str.indexOf(Str.charAt(6)));
//will check for occurrence of 'o' from index 5
System.out.println(Str.indexOf('o', 5));
//will check for occurrence of Str1 from index 0
System.out.println( Str.indexOf(Str1));
//will check for occurrence of Str1 from index 10
System.out.println( Str.indexOf(Str1,10));
//will check for occurrence of Str2 from index 0
System.out.println( Str.indexOf(Str2));

Output
4
0
10
0
12
-1

9. Finding the last index Position of a string/character in another String object– lastIndexOf( )

This function either takes single or two parameters and will return an integer.
The lastIndexOf() method is used to find the last Index position of a character in another String
object.
This function will return the last index position if the character looked for in another String object
exists. If it does not exist this method will return -1.
Example:
String Str = new String("Hello Hello Hello");
String Str1 = new String("Hello");

//will check for the last occurrence of ‘o’


System.out.println(Str.lastIndexOf( 'o' ));
//will check for the last occurrence of the String str1
System.out.println(Str.lastIndexOf( Str1 ));

//will check for the last occurrence of ‘o’ only up to the 12 th index
System.out.println(Str.lastIndexOf( 'o',12 ));
//will check for the last occurrence of Str1 only up to the 8th index
System.out.println(Str.lastIndexOf( Str1,8 ));

STRINGS [CELINE BIJU – SISHYA] Page 7


Output
16
12
10
0

10. Extract single character from a string – charAt()


The charAt() method is used to extract a single character by specifying the position of the
character.
This method will return a character.
Example :
String str = "Auto Finance";
System.out.println( str.charAt(5) );

Output
F

11. Extracting part of a string.


The substring() is used to extract part of a string by specifying the start position and end
position.
This method will return a String.

Example:
String Str = new String("Welcome_to_Learning_Java");
//will extract characters from the 10th position till the end of the string
System.out.println(Str.substring(10) );
//will extract characters from the 10th positon till the index (15-1)
System.out.println(Str.substring(10, 15) );
Output
-Learning Java
-Lear

12. Replacing characters in a string


The replace() method is used to replace a character by another character or to replace a String by
another String at all its occurrences in the given String.
This method will return a String .
Example
String str = "Word Word Word";
String str1=str.replace('o', 'a');
STRINGS [CELINE BIJU – SISHYA] Page 8
System.out.println(str1);
String str2 = "Auto Loan Auto Loan";
System.out.println(str2.replace("Auto", "Fixed"));
Output
Ward Ward Ward
Fixed Loan Fixed Loan

13. Converting a string to upper case.


The toUpperCase() method is used to convert a string to upper case letters. This method will
return a String.
Example
String str = "Cheap Car Insurance";
System.out.println(str.toUpperCase());
System.out.println(str);
String str1= str.toUpperCase();
System.out.println(str1);

Output
CHEAP CAR INSURANCE
Cheap Car Insurance
CHEAP CAR INSURANCE

14. Converting a string to lower case.


The toLowerCase() method is used to covert a string to lower case letters.
String str = "Insurance ";
System.out.println(str.toLowerCase());
Output
insurance

15. concat()

This function is applied to concatenate(join) two strings together.


Example
String x=”Computer ”;
String y=”Applications”;
String z=x.concat(y);
System.out.println(z);
System.out.println(“Foot”.concat(“ball”));

Output
Computer Applications
Football

STRINGS [CELINE BIJU – SISHYA] Page 9


16. trim()

This function is used to remove the blanks from either side of the string. Other blanks which are
present in between words will remain unchanged.
Syntax
String str1=String str2.trim();
Example
String str=” Computer Applications “;
String str1=str.trim();
System.out.println(str1);
Output
Computer Applications(no leading and trailing space)

17. To return the String representation of any primitive data type.

Syntax

String.valueOf(any primitive data type)

This method is a static function and it returns the string representation of the primitive data type
passed as a parameter.
Example :
double d = 1029.939;
boolean b = true;
long l = 1232874;
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };
String str1=String.valueOf(d);
String str2=String.valueOf(b);
System.out.println(str1);
System.out.println(str2);
System.out.println(String.valueOf(l));
System.out.println(String.valueOf(arr));

This produces the following result:

1029.939
true
1232874
Abcdefg

STRINGS [CELINE BIJU – SISHYA] Page 10

You might also like