Strings in Java
• Strings in Java are also a reference type.
– They are similar to an array of characters in that
they represent an ordered sequence of characters
with positions numbered from 0.
– String constants are enclosed in double quotes.
• Example:
String message = "Hello World!";
System.out.println( message );
• The class String provides many useful methods.
1
Comparison with character arrays
• Although a String has many similarities to an array of
characters, there are some important differences.
• You don’t need to use new to create a string unless you want to
use one of the String class constructors
String s1 = "Hello!";
String s2 = new String("Hello!");
• You DO NOT use [] to access the characters in the string.
• The contents of a String cannot be changed after it has been
created.
– You can have a String variable refer to a different string,
but you cannot change characters within the original string.
– There is NO equivalent to:
char[] x = new char[] {'h','e','l','l','o'};
x[2] = 'q';
2
Conversion to/from character arrays
• To convert from a character array to a String:
char[] x = new char[] {'h','e','l','l','o'};
String s1 = new String( x );
• To convert from a String to a character array:
char[] x = aString.toCharArray( );
3
Useful String methods
• Suppose we have
String message = "Hello World!";
• To find the length of a string:
int theStringLength = message.length();
• To find the character at position i (numbered from
0):
int i = 4;
char theChar = message.charAt( i );
4
Useful String methods
• Substrings:
– The substring method returns a String consisting
of the characters starting from the first position
inclusive up to but NOT including the second
position:
String str = "abcdefghijklmno";
String str2 = str.substring( 2, 5 );
– Result is "cde“
• Case changes
toLowerCase( ), toUpperCase( )
5
Comparing Strings
• A String is a reference type and so they are NOT compared
with ==.
• The String class has a method compareTo() to compare 2
strings.
– The characters in each string are compared one at a time
from left to right, using the collating sequence.
– The comparison stops after a character comparison results in
a mismatch, or one string ends before the other.
• If str1 < str2, then compareTo() returns an int < 0
• If str1 > str2, then compareTo() returns an int > 0
– If the character at every index matches, and the strings are
the same length, the method returns 0
6
Comparing Strings
• What is the value of result for these examples?
• Example 1:
String str1 = "abcde" ;
String str2 = "abcfg" ;
int result = str1.compareTo(str2);
• Example 2:
String str1 = "abcde" ;
String str2 = "ab" ;
int result = str1.compareTo(str2);
7
Comparison of 2 strings:-
(BY THE HELP OF == OPERATOR)
class HelloWorld
{
public static void main(String[] args)
{
String s1="hello";
String s2="hello";
if(s1==s2)
System.out.println("both are equal");
}
}
o/p:- both are equal.
class HelloWorld
{
public static void main(String[] args)
{
String s1="hello";
String s2=new String("hello“);
if(s1==s2)
System.out.println("both are equal");
Else
System.out.println(“both are not equal”);
}
}
o/p:- both are not equal.
Comparison of 2 strings by the help
of .equls() Method
class HelloWorld
{
public static void main(String[] args)
{
String s1="hello";
String s2="hello";
if(s1.equals(s2))
System.out.println("both are equal");
else
System.out.println(“both are not equal”);
}
}
o/p:- both are equal.
10
Difference between == and equals()
while comparing strings
== operator compares the references of
the string objects.
It doesnot compare the content of the
objects.
Equals() compares the contents.
What is String constant pool?
SCP is a separate block of memory
where the string objects are held by
jvm.
If a string object is created directly
using assignment operator as String 11
s1=“hello”;
Difference between the following statements
String s=“hello”;
String s=new String(“hello”);
1.In the first statement assignment operator
is used to assign the string literal to
string variable s.
2.In this case jvm first of all checks whether
the same object is already available in the
string pool or not.
3.If it is available then it creates another
refernce to it.
4.If the same object is not available then it
creates another object with the content 12
Immutability of strings
1. Objects can be of 2 types immutable and mutable.
2. In Java, String objects are immutable. Immutable
simply means unmodifiable or unchangeable.
3. Once String object is created its data or state can't
be changed but a new String object is created.
4. class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the
string at the end
System.out.println(s);//will print Sachin because
strings are immutable objects
}
} //o/p:-Sachin 13
Now it can be understood by the diagram given below. Here Sachin is
not changed but a new object is created with Sachin Tendulkar. That
is why String is known as immutable.
14
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
o/p:-Sachin Tensdulkar
15
1:- Search for a given string in an array of strings.
16